Binding command in UWP

南楼画角 提交于 2019-12-04 19:15:28
Jay Zuo

For different objects in different pages, the MenuFlyoutItem and its Command would be different, so usually, we won't put the MenuFlyout in Application.Resources. But if you can make sure the MenuFlyoutItems used in different Pages are the same, then the following might be a solution for you.

Firstly, in App.xaml, set Binding for Command:

<Application.Resources>
    <MenuFlyout x:Key="LessonFlyout">
        <MenuFlyoutItem Text="Edit" Command="{Binding EditCommand}" />
        <MenuFlyoutItem Text="Delete" Command="{Binding DeleteCommand}" />
    </MenuFlyout>
</Application.Resources>

Then implement I​Command Interface like the RelayCommand.cs in official sample.

After this, we need to implement EditCommand and DeleteCommand in view model so that the binding can work. For example:

public class ViewModel
{
    public ICommand EditCommand { get; set; }

    public ICommand DeleteCommand { get; set; }

    public ViewModel()
    {
        EditCommand = new RelayCommand(() =>
        {
            //TODO
            System.Diagnostics.Debug.WriteLine("EditCommand");
        });
        DeleteCommand = new RelayCommand(() =>
        {
            //TODO
            System.Diagnostics.Debug.WriteLine("DeleteCommand");
        });
    }
}

And then attach the MenuFlyout like:

StackPanel thisSender = sender as StackPanel;
thisSender.DataContext = new ViewModel();
FlyoutBase.SetAttachedFlyout(thisSender, Application.Current.Resources["LessonFlyout"] as MenuFlyout);
FlyoutBase.ShowAttachedFlyout(thisSender);

The ViewModel used here is just for example, usually you should have a view model for your page and if so there is no need to set DataContext when attaching the MenuFlyout. Setting EditCommand and DeleteCommand in your page's view model should be enough to work.


For the following error:

The member "Icon" is not recognized or is not accessible.
The property 'Icon' was not found in type 'MenuFlyoutItem'.

This is because your project is targeting a version earlier than Build 15063. In Icon property, we can find Additional features and requirements that indicates this property is introduced in Windows 10 Creators Update (v10.0.15063.0). So to use this property, please make sure you are targeting Build 15063 or later.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!