WPF - Handle an ApplicationCommand in the ViewModel

后端 未结 1 856
温柔的废话
温柔的废话 2021-01-12 16:05

I bet this has been answered many times over, but...

For a simple situation where a button on a UserControl has its command property set to something like Find (Appl

相关标签:
1条回答
  • 2021-01-12 16:27

    The purpose of commands is to decouple the code which generates the order from the code which executes it. Therefore: if you want tight coupling, you should better do it through events:

    <UserControl ... x:Class="myclass">
        ...
        <Button Click="myclass_find" .../>
        ...
    </UserControl>
    

    For loose coupling you need to add a CommandBinding to your UserControl:

    <UserControl ... >
        <UserControl.DataContext>
            <local:MyViewModel/>
        </UserControl.DataContext>
    
        <UserControl.CommandBindings>
            <Binding Path="myFindCommandBindingInMyViewModel"/>
        </UserControl.CommandBindings>
        ...
        <Button Command="ApplicationComamnd.Find" .../>
        ...
    </UserControl>
    

    (not sure about the syntax)

    Or you can add a CommandBinding to your UserControl's CommandBindings in the constructor, taking the value from the ViewNodel:

    partial class MyUserControl : UserControl
    {
        public MyUSerControl()
        {
            InitializeComponent();
            CommandBinding findCommandBinding = 
                      ((MyViewModel)this.DataContext).myFindCommandBindingInMyViewModel;
            this.CommandBindings.Add(findCommandBinding);
        }
    }
    
    0 讨论(0)
提交回复
热议问题