簡體   English   中英

從 Flyout XAML 中的按鈕訪問 Flyout

[英]Access Flyout from button inside Flyout XAML

我覺得這是一個新手 XAML 問題,但這里是。

我想要做什么:我正在開發一個 Windows Phone 8.1 應用程序,我想向自定義彈出按鈕添加功能,以便連續兩次單擊彈出按鈕中的同一個菜單按鈕,關閉彈出按鈕。 示例:用戶單擊彈出窗口中的“轉到設置”菜單項。 如果用戶現在再次單擊它,則意味着我們已經在設置菜單中,因此我只想關閉彈出窗口。

問題:我的問題是我需要某種方法才能在單擊彈出按鈕內的按鈕時調用彈出窗口內的代碼。 我沒有選擇在此處執行任何代碼隱藏,因為我正在使用 MVMCross 和 Xamarin(並且我不想將特定於 Windows 手機的邏輯移動到通用的所有平台視圖模型中)。

到目前為止的嘗試:我嘗試通過制作一個繼承自 Button 的自定義按鈕來解決這個問題。 當按鈕加載時,一個事件被訂閱到它的點擊事件。 發生這種情況時,我嘗試通過遞歸查看按鈕的父級(然后是父級的父級)來獲取彈出按鈕的句柄,直到找到它為止。 ...這不起作用,因為我從來沒有將 Flyout 作為父項,而是獲得了一個 Flyout-presenter(它不能讓我訪問我的自定義彈出),所以我無法在這里調用我想要的函數。

我嘗試制作一個繼承自 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); }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM