从Flyout XAML中的按钮访问Flyout
本文关键字:Flyout 按钮 访问 XAML | 更新日期: 2024-09-22 18:16:40
我觉得这是一个新手XAML问题,但现在开始。
我想做的事:我正在开发一个Windows Phone 8.1应用程序,我想为自定义弹出型按钮添加功能,以便连续两次单击弹出型按钮中的同一菜单按钮,关闭弹出型按钮。示例:用户单击弹出按钮中的"转到设置"菜单项。如果用户现在再次单击它,这意味着我们已经在设置菜单中了,因此我只想关闭弹出按钮。
问题:我的问题是,当点击弹出型按钮时,我需要一些方法来调用弹出型按钮内的代码。由于我正在使用MVVMCross和Xamarin(我不想将windows phone特定的逻辑转移到所有平台视图模型的通用逻辑中),因此我无法在这里执行任何代码。
迄今为止已尝试:我尝试通过制作一个从button继承的自定义按钮来解决这个问题。当按钮加载时,一个事件被订阅到其所点击的事件。当这种情况发生时,我试图通过递归地查看按钮的父级(然后是父级的父级)来获得弹出按钮的句柄,直到找到为止。…这不起作用,因为我从来没有作为家长获得Flyout,而是获得了一个Flyout演示器(它不允许我访问我的自定义弹出按钮),所以我无法在这里调用我想要的函数。
我尝试过制作一个从Button继承的自定义"FlyoutButton"。这个按钮有一个可以在XAML中设置的弹出按钮的DependencyProperty,所以我在按钮内部有一个弹出按钮的句柄。然而,当我尝试这样做时,我只得到了一个异常"System.Void不能从C#中使用",我真的不明白为什么会得到这个异常。下面是我的代码。
我的代码: XAML代码段:
<Button.Flyout>
<controls:MainMenuFlyout x:Name="test"
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<controls:MainMenuButton MainMenuFlyout="{Binding ElementName=test}" Grid.Row="0"/>
<controls:MainMenuButton MainMenuFlyout="{Binding ElementName=test}" Grid.Row="0"/>
<controls:MainMenuButton MainMenuFlyout="{Binding ElementName=test}" Grid.Row="0"/>
<controls:MainMenuFlyout />
<Button.Flyout />
C#:
public class MainMenuButton : Button
{
public static DependencyProperty MainMenuFlyoutProperty = DependencyProperty.Register("MainMenuFlyout", typeof(MainMenuFlyout), typeof(MainMenuButton), new PropertyMetadata(string.Empty, MainMenuFlyoutPropertyChangedCallback));
public static void SetMainMenuFlyout(UIElement element, MainMenuFlyout value)
{
element.SetValue(MainMenuFlyoutProperty, value);
}
public MainMenuFlyout GetMainMenuFlyout(UIElement element)
{
return (MainMenuFlyout)element.GetValue(MainMenuFlyoutProperty);
}
private static void MainMenuFlyoutPropertyChangedCallback(DependencyObject dependencyObject,
DependencyPropertyChangedEventArgs e)
{
}
}
依赖属性声明错误。应该是这样的,使用常规属性包装器而不是静态getter和setter方法,并将null
作为默认属性值,而不是string.Empty
:
public static DependencyProperty MainMenuFlyoutProperty =
DependencyProperty.Register(
"MainMenuFlyout", typeof(MainMenuFlyout), typeof(MainMenuButton),
new PropertyMetadata(null, MainMenuFlyoutPropertyChangedCallback));
public MainMenuFlyout MainMenuFlyout
{
get { return (MainMenuFlyout)GetValue(MainMenuFlyoutProperty); }
set { SetValue(MainMenuFlyoutProperty, value); }
}