Is there a way reuse the same context menu (MenuFlyout) within an Xaml using resources or similar? #8303
-
I want to use the same context menu in 3 different controls within a page. Can I define the menu in Xaml resources and re-use it? Or the only way is to do it in code-behind? |
Beta Was this translation helpful? Give feedback.
Answered by
gautambjain
Mar 21, 2023
Replies: 2 comments
-
Resolved this. All controls were list views. I could achieve this by adding the ContextFlyout inside the DataTemplate of the list view item like below:
|
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
gautambjain
-
Hey, I think I have a better approach. Here's a snippet of my code: <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<MenuFlyout x:Key="TableContextFlyout">
<MenuFlyoutItem
Name="TableContextFlyout_View"
x:Uid="TableContextFlyout_View"
Command="{Binding SaveDataCommand}">
<MenuFlyoutItem.Icon>
<SymbolIcon Symbol="View" />
</MenuFlyoutItem.Icon>
</MenuFlyoutItem>
<MenuFlyoutItem
Name="TableContextFlyout_Add"
x:Uid="TableContextFlyout_Add"
Command="{Binding AddCommand}">
<MenuFlyoutItem.Icon>
<SymbolIcon Symbol="Add" />
</MenuFlyoutItem.Icon>
</MenuFlyoutItem>
<MenuFlyoutItem
Name="TableContextFlyout_Edit"
x:Uid="TableContextFlyout_Edit"
Command="{Binding EditCommand}">
<MenuFlyoutItem.Icon>
<SymbolIcon Symbol="Edit" />
</MenuFlyoutItem.Icon>
</MenuFlyoutItem>
<MenuFlyoutItem
Name="TableContextFlyout_Delete"
x:Uid="TableContextFlyout_Delete"
Command="{Binding DeleteCommand}">
<MenuFlyoutItem.Icon>
<SymbolIcon Symbol="Delete" />
</MenuFlyoutItem.Icon>
</MenuFlyoutItem>
</MenuFlyout>
</ResourceDictionary> namespace WinUiDemo.Views;
public sealed partial class DepartmentInfoPage : Page
{
private static bool _isMenuFlyoutInitialized = false;
public DepartmentInfoViewModel ViewModel
{
get; set;
}
public DepartmentInfoPage()
{
ViewModel = App.GetService<DepartmentInfoViewModel>();
InitializeComponent();
DataContext = ViewModel;
if (!_isMenuFlyoutInitialized)
{
InitializeMenuFlyout();
_isMenuFlyoutInitialized = true;
}
}
private void InitializeMenuFlyout()
{
var menuFlyout = (MenuFlyout)Application.Current.Resources["TableContextFlyout"];
foreach (var item in menuFlyout.Items)
{
if (item is MenuFlyoutItem menuItem)
{
menuItem.DataContext = ViewModel;
}
}
}
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Resolved this.
All controls were list views. I could achieve this by adding the ContextFlyout inside the DataTemplate of the list view item like below: