WPF: How to bind to the name property - wpf

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

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 !

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

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!

Related

TextBox ConvertBack event doesn't fire for XML element

ValueFormattingConverter.Convert is called with the XmlElement. ConvertBack is never called. Why? Is there some obligation to pass binding directives down the chain? Is the use of the TextBox overriding its own binding settings? What can be done?
My TextBox
<TextBox Width="200"
Text="{Binding Path=., Converter={StaticResource valueFormattingConverter}}",
Mode=TwoWay,
NotifyOnSourceUpdated=True,
NotifyOnValidationError=True,
UpdateSourceTrigger=PropertyChanged}" />
Usage is rather convoluted. Starting at the top, we provide an XML element to a tab.
<TabItem.DataContext>
<Binding Source="{StaticResource mcf}",
XPath="mdf/press_information"/>
</TabItem.DataContext>
That tab contains a ItemsControl which builds TextBoxes through this ControlChooser which passes the binding along.
<ItemsControl.ItemTemplate>
<DataTemplate>
<W3V:ControlChooser RelativeSource="{RelativeSource AncestorType=W3V:ObjectList}",
Content="{Binding}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
My converter class header. Convert method is called. ConvertBack never.
[ValueConversion(typeof(XmlElement), typeof(string))]
public class ValueFormattingConverter : IValueConverter
EDIT: The chosen answer basically says Path=. doesn't support 2-way binding. I believe it is the correct answer to the question. Very helpful to know, but "can't do that" doesn't solve the larger problem. So I have laid out the larger question here: Means of generating an editable form from XML.
The binding direction to source won't work with a {Binding Path=.}. This is because there is no bound property, but just the binding source object.
Hence there will never be a source update, and the ConvertBack method is never called, because that would mean to replace the source object.
In order to make your code work, you would have to bind to some property:
<TextBox Text="{Binding Path=SomeElement, ...}"/>

WPF Binding - Self Binding with its own DataContext

Anyone got a situation to bind the same DataContext to Text property (for example) in TextBlock.
I have to assign the DataContext to reflect some trigger based on the Data values from Datacontext in my style. at the same time, i need to bind with the same DataContext object to get the Text Property After applying some conversion on either IValueConverter/IMultivalueConverter.
As i know {Binding}, just bind with the current datacontext. But in the same scenario how to use converter with it?
Any suggestions will be appreciated.
<TextBlock Style="{StaticResource DataEntryTextBlock1}" Grid.Row="1"
DataContext="{Binding MyField1}"
Text="{Binding MyField1, Converter={StaticResource myConverter}}">
</TextBlock>
This XAML script does not work, as the Text binding is trying to look for the MyField1 variable inside the MyField1.
Thanks,
Vinodh
{Binding} is equivalent to {Binding Path=.} so in you case you can use
Text="{Binding Path=., Converter={StaticResource myConverter}}"
Binding.Path on MSDN
Optionally, a period (.) path can be used to bind to the current source. For example, Text="{Binding}" is equivalent to Text="{Binding Path=.}"

How to bind to a StaticResource with a Converter?

I want to use a Converter to change the value of a StaticResource before assigning it to a property. Is there a way to simulate a Binding that will just set the value of the StaticResource after converting it?
Something like {Binding Value={StaticResource myStatic}, Converter={StaticResource myConverter}}?
This works:
<TextBox Text="{Binding Source={StaticResource myStatic},
Converter={StaticResource myConverter},
Mode=OneWay}" />
Note that you have to bind one way, because the binding requires a path attribute otherwise. This makes sense, as otherwise the binding would have to replace the whole resource...

WPF Binding to ElementName inside ItemsControl

I have a checkbox, and an ItemsControl populating several DataGrids the following way:
<Checkbox Content="Birthday Column Visible" x:Name="UI_BirthdayVisibleCB" />
<ItemsControl ItemsSource="{Binding Path=ParentsCollection}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Children}">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Birthday" Width="120" Visibility="{Binding IsChecked, ElementName=UI_BirthdayVisibleCB, Converter={StaticResource BoolToVis}}" >
...
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Rest of closing tags>
This creates binding output errors as it tries to find IsChecked on the DataGridTemplateColumn. If I try to search for a Relative Ancestor I receive the exception:
Binding.RelativeSource cannot be set while using Binding.ElementName.
I have a ViewModel, and stick to MVVM mostly, but in this case I'd really like to keep the column visibilities on the View layer. Note that BoolToVis just converts Boolean to Visibility.
Edit
Here is an example of what I'm trying to do:
<DataGridTemplateColumn Header="Birthday" Visibility="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:MyView} }, Path=IsChecked, ElementName=UI_BirthdayVisibleCB, Converter={StaticResource BoolToVis}}" />
It compiles but doesn't run however, it throws the exception above.
You are using RelativeSource, which can't be mixed with ElementName, but you once you have the correct RelativeSource, you can drill down deeper using path.
e.g.
Visibility="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:MyView} }, Path=UI_BirthdayVisibleCB.IsChecked, Converter={StaticResource BoolToVis}}"
presumably you have some xaml like this:
<UserControl class="MyView" ... >...<CheckBox Name="UI_BirthdayVisibileCB"/> ...
The above binding should find this UserControl by type based on RelativeSource, then it will try to find a property named UI_BirthdayVisibleCB, which it won't find because WPF XAML implements this named element as a field.
The easy work around is to go into your codebehind and expose a property for it.
public object BirthdayVisibileCB_4_binding {
get { return UI_BirthdayVisibileDB; }
}
and bind to it instead:
Visibility="{Binding RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type local:MyView} },
Path=BirthdayVisibileCB_4_binding.IsChecked, Converter={StaticResource BoolToVis}}"
Yes, it kind of a pain to do this, but MVVM only matches WPF so far... its not a great fit, its only the best fit we have around.
If you want to try RelativeSource, you have to remove ElementName from the declaration:
However, only one of the three
properties, ElementName, Source, and
RelativeSource, should be set for each
binding, or a conflict might occur.
This property throws an exception if
there is a binding source conflict.
http://msdn.microsoft.com/en-us/library/system.windows.data.binding.elementname.aspx
Your usage of ElementName seems correct, so I'll continue to look at the problem if you prefer that over RelativeSource.

ValueConverter not invoked in DataTemplate binding

I have a ComboBox that uses a DataTemplate. The DataTemplate contains a binding which uses an IValueConverter to convert an enumerated value into a string. The problem is that the value converter is never invoked. If I put a breakpoint in StatusToTextConverter.Convert(), it never is hit.
This is my XAML:
<ComboBox ItemsSource="{Binding Path=StatusChoices, Mode=OneWay}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={StaticResource StatusToTextConverter}}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
I thought this is how one implicitly binds to the value a DataTemplate is presenting. Am I wrong?
Edit: For context: I intend to display an Image in the DataTemplate alongside that TextBox. If I can't get the TextBox binding to work, then I don't think the Image will work, either.
In some circumstances you must explicitly supply a Path for a Binding. Try this instead:
<TextBlock Text="{Binding Path=.,Converter={StaticResource StatusToTextConverter}}"/>

Resources