WPF - Calling ApplicationCommand in ViewModel

I bet it has been answered many times, but ...

For a simple situation, when a button in UserControl has a property of its command set to something like Find (ApplicationCommands.Find), how would the ViewModel process this command? Usually I see command handlers connected using CommandBinding that are added to the CommandBindings collection on a UIElement, but my ViewModel is not inferred from the UIElement (if?). The teams themselves do not set up events for notification when they were executed, so where should I connect to get this information?

EDIT: I would like to use WPF to solve the problem, if possible. I know that there are many frameworks available for this kind of thing, but I would like the code to be simple.

EDIT2: Includes sample code.

<UserControl> <UserControl.DataContext> <local:MyViewModel/> </UserControl.DataContext> <Button Command="Find"/> </UserControl> 

Where:

 class MyViewModel { // Handle commands from the view here. } 

I could add a CommandBinding to a UserControl that handled Executed, and then call the hypothetical Find method in MyViewModel, which does the actual work, but this redundant and unnecessary code. I would prefer the ViewModel itself to handle the Find command. One possible solution would be for MyViewModel to be inferred from UIElement, but it seems like an intuitive interface.

+6
command wpf mvvm
source share
1 answer

The purpose of the commands is to untie the code that generates the order from the code that executes it. Therefore: if you need a tight connection, you better do it through events:

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

For a free connection, 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 syntax)

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

 partial class MyUserControl : UserControl { public MyUSerControl() { InitializeComponent(); CommandBinding findCommandBinding = ((MyViewModel)this.DataContext).myFindCommandBindingInMyViewModel; this.CommandBindings.Add(findCommandBinding); } } 
+4
source share

All Articles