Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understand WPF Binding CommandParameter="{Binding}"

Tags:

binding

wpf

Maybe this is a dumb question, but I can't find the answer: in the following xaml what does CommandParameter binding to? Or in general, what does "{Binding}" mean?

<Button Command="{Binding DataContext.DeleteCommand, ElementName=List}" 
        CommandParameter="{Binding}"/>
like image 296
Bolu Avatar asked Mar 21 '11 12:03

Bolu


People also ask

What is WPF CommandParameter?

CommandParameter - represents a user-defined data value that can be passed to the command when it is executed. CommandTarget - the object on which the command is being executed.

How does WPF binding work?

Data binding is a mechanism in WPF applications that provides a simple and easy way for Windows Runtime apps to display and interact with data. In this mechanism, the management of data is entirely separated from the way data. Data binding allows the flow of data between UI elements and data object on user interface.

How many types of binding are there in WPF?

WPF binding offers four types of Binding. Remember, Binding runs on UI thread unless otherwise you specify it to run otherwise. OneWay: The target property will listen to the source property being changed and will update itself.

How do you use a CommandParameter?

Passing a parameter to the CanExecute and Execute methods A parameter can be passed through the "CommandParameter" property. Once the button is clicked the selected address value is passed to the ICommand. Execute method. The CommandParameter is sent to both CanExecute and Execute events.


2 Answers

{Binding ...} is a MarkupExtension.
In its usual form it takes a Path like {Binding Path=someProperty, ...} (or its short form {Binding someProperty, ...}).
So the path in {Binding} is empty which means the Binding is bound to whatever Source there is for the Binding. This might be a little easier to understand if you know, that {Binding} is actually the same as {Binding DataContext,RelativeSource={RelativeSource Self}}.

So in your case CommandParameter gets the value of the current DataContext of the Button.

like image 128
Markus Hütter Avatar answered Oct 03 '22 20:10

Markus Hütter


An Empty {Binding} will pass the current DataContext of the control to the Executed and CanExecute methods respectively.

like image 44
biju Avatar answered Oct 03 '22 22:10

biju