I did not find a way to do this in XAML, but I did it in code. Here is my approach.
Firstly, I wanted to do this for all items in an ItemsControl . So I had XAML:
<ListBox x:Name="_events" ItemsSource="{Binding Path=Events}"> <ListBox.ItemTemplate> <DataTemplate DataType="{x:Type Events:EventViewModel}"> <TextBlock Name="ActualText" /> </DataTemplate> </ListBox.ItemTemplate> </ListBox>
Then, in the code behind the construct, I subscribe to ItemContainerGenerator :
InitializeComponent(); _events.ItemContainerGenerator.StatusChanged += OnItemContainerGeneratorStatusChanged;
This method is as follows:
private void OnItemContainerGeneratorStatusChanged(object sender, EventArgs e) { if (_events.ItemContainerGenerator.Status!=GeneratorStatus.ContainersGenerated) return; for (int i = 0; i < _viewModel.Events.Count; i++) {
If you have only one element to set the binding, then the code will be a little easier.
<TextBlock x:Name="_text" Name="ActualText" />
And in the code behind:
var binding = new Binding(path) { Source = bindingSourceObject }; _text.SetBinding(TextBlock.TextProperty, binding);
Hope this helps someone.
source share