Reputation: 15377
I use a lot of bindings in XAML and sometimes I use path= in a binding and sometimes not. In which cases do I need the path= and when can I omit this?
Upvotes: 24
Views: 19477
Reputation: 43021
This is due to the fact that the Binding class has a default constructor, used when you have bindings like {Binding FallbackValue='HelloWorld', Path=MyProperty}
and a constructor that has a single argument Path.
So when there is a list of property/value pairs the binding is created as
new Binding(){
Path="MyProperty"
ElementName="MyElement"
}
The second form is used for bindings like {Binding MyProperty, ...}
. In this case the binding is created as
new Binding("MyProperty"){
ElementName = "MyElement",
...
}
It's always correct (and possibly more correct) to specify Path=, but you can get away without it.
Upvotes: 12
Reputation: 84824
It can always be omitted as it's the default property of the Binding XAML extension. It's only specified explicitly for clarity when multiple properties are used.
Upvotes: 15
Reputation: 2947
Path is used to specify the name of the property of the underlying object to bind to.
When you bind to the DataContext, you can omit Path:
{Binding MyProperty}
{Binding Path=MyProperty}
When you need to specify a source other than the DataContext you can use Source
, RelativeSource
, or ElementName
to refer to the object, so you will usually have to specify to which property of it you want to set your binding:
<Button Background="{Binding ElementName=refButton, Path=Background}"/>
<TextBlock Width="{Binding RelativeSource={RelativeSource Self}, Path=Parent.ActualWidth}"/>
Upvotes: 7
Reputation: 47995
Like Richard Szalay said, it is optional if it is the first property. But in my opionion it is easier to read if you enter the path property. Also the code highlighting looks better.
Upvotes: 3
Reputation: 35564
You can always omit the Path= when you write the path to the property directly behind the Binding statement.
{Binding MyProperty}
is the same as
{Binding Path=MyProperty}
When you inline the path to the property you need to specify it with Path=
{Binding FallbackValue='HelloWorld', Path=MyProperty}
Upvotes: 4