我覺得這是一個菜鳥XAML的問題,但是在這裏。從Flyout XAML裏面的按鈕訪問Flyout
我想做什麼: 我開發了Windows Phone 8.1應用程序,我想將功能添加到自定義 - 彈出,這樣點擊在彈出的兩次相同的菜單按鈕排,關閉飛出。 示例:用戶單擊彈出窗口中的「轉到設置」菜單項。如果用戶再次點擊它,這意味着我們已經在設置菜單中,因此我只想關閉該彈出窗口。
問題: 我的問題是,我需要某種方式能夠在彈出窗口中調用代碼,當它裏面的按鈕被點擊。因爲我正在與MVVMCross和Xamarin合作(我不想將windows-phone特定的邏輯轉移到通用平臺視圖模型中),所以我沒有選擇在這裏執行任何代碼的問題。
迄今爲止嘗試: 我已經嘗試通過使自定義按鈕從按鈕繼承來解決此問題。當按鈕加載時,一個事件被訂閱到它的tapped事件。當發生這種情況時,我試圖通過遞歸地查看按鈕的父級(然後是父級的父級),直到找到它,嘗試獲取彈出窗口的句柄。 ...這是行不通的,因爲我從來沒有把Flyout作爲父母,而是我得到了Flyout-Presenter(它不允許我訪問我的自定義彈出窗口),所以我無法調用我想要的功能。
我試着製作一個自定義的「FlyoutButton」繼承自Button。這個按鈕有一個可以在XAML中設置的Flyout的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)
{
}
}
你的依賴屬性聲明是錯誤的。您應該聲明一個具有調用GetValue和SetValue的getter/setter的'public MainMenuFlyout MainMenuFlyout'屬性,而不是聲明靜態getter和setter方法。 – Clemens
除此之外'string.Empty'對於MainMenuFlyout類型的屬性來說是一個無效的默認值。 – Clemens
非常感謝!你的反饋是正確的,並且這些改變奏效了! – oPolo