简体   繁体   中英

WPF Code-behind equivalent

When developing, I like to try and understand more than "just do this". Especially with WPF, I like to understand BOTH aspects of the bindings... both from the GUI (xaml) and from the code-behind. That being said, I am wondering what the code equivalent would be for the following.

I have a ViewModel with some pre-defined "ICommand" instances, such as add, edit, save, cancel, exit, whatever -- and they work as expected. Now, looking at the binding of the View (Window) that has a button on it, I have it's binding to the commands, something like.

<Button Command="{Binding ExitCommand}" Content="Exit" ... />

and this properly does what I expect for allowing the form to exit (and do whatever else I'm playing with).

What would the code-behind look like for this. I know that with properties, such as IsEnabled or IsVisible are bound to dependency object / properties, but I don't understand the correlation when binding to a command's execution. Thanks.

You create the Command Binding the same way you would any other binding in code behind.

For example,

Binding b = new Binding();
b.Source = myViewModel;
b.Path = new PropertyPath("ExitCommand");
MyButton.SetBinding(Button.CommandProperty, b);

Command bindings expect to be bound to an object of type ICommand . When they get executed, such as on a Button Click, they first call ICommand.CanExecute() and if that is true then they call ICommand.Execute() . If the CommandParameter property is set then that is used when evaluating CanExecute and Execute

With WPF Buttons that have a Command binding, the IsEnabled property is automatically bound to the result of ICommand.CanExecute . The CanExecute method is run once when the button is first loaded, and run again anytime the Command Binding changes.

If you want it to update more frequently, such as when the CommandParameter changes, you need to hook up something extra to update the binding when the CommandParameter changes. Most RelayCommands I see have this built-in, such as MVVM Light's RelayCommand , althought other commands such as Microsoft PRISM's DelegateCommand do not have this behavior by default.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM