Reputation: 5950
Can i bind to the name property? This does not seem to work:
<TextBlock Name="FordPerfect" Text="{Binding Path=Name, Mode=OneWay}"/>
Am i doing something wrong?
Edit:
Adding ElementName=FordPerfect"
solved the issue. What i don't understand is why only binding to Name
required this while other properties don't.
Note: Moved the second (design) issue to another question (where i should have placed in the first time...)
Thanks
Upvotes: 0
Views: 20807
Reputation: 30458
The issue you're having is a Binding
, by default, uses the DataContext
of the element it's used on as its source. However you want the binding source to be the TextBlock
element itself.
WPF has a class called RelativeSource
which, as its name implies, sets the source relative to the binding. One of the relations you can choose is Self
which does exactly what you want: sets the source of the binding to the element it's used on.
Here's the code:
<TextBlock Name="FordPerfect" Text="{Binding Name, RelativeSource={RelativeSource Self}}" />
Since you're already setting the source with RelativeSource
, you don't need to specify ElementName
. You also don't need Mode=OneWay
as a TextBlock.TextProperty
already defaults to one-way since it's output-only.
Hope this helps!
Upvotes: 0
Reputation: 7906
you could have more easily done this:
<TextBlock Name="FordPerfect"
Text="{Binding Name, Converter={StaticResource conv}, Mode=OneWay, RelativeSource={RelativeSource Self}}"/>
As to why: that textbox' DataContext is not automatically the TextBox itself. So binding to Name
tries to bind to whateverObjectInDataContext.Name
. So either you set the DataContext beforehand like:
<TextBlock Name="FordPerfect" DataContext={Binding RelativeSource={RelativeSource Self}}
Text="{Binding Name, Converter={StaticResource conv}, Mode=OneWay}"/>
... or directly set a Source for the Binding
Upvotes: 2
Reputation: 626
I would try this :
<TextBlock Name="FordPerfect"
Text="{Binding ElementName=FordPerfect, Path=Name, Converter={StaticResource conv}, Mode=OneWay}"/>
This way, your TextBlock will be the context of the binding. If it does not work, watch the Output window, you should find a binding error !
Upvotes: 6