In our C# WPF application (with the Caliburn.Micro framework) we have a View and a ViewModel. In the ViewModel we have a string-property and I want to show this string inside each child of an ItemsControl (these items have their own ViewModel). I know I could just pass the property to each of these items, but that shouldn't be needed.
So, here is the relevant part of the ViewModel:
using System;
...
namespace NatWa.MidOffice.Modules.Financien.Views
{
public class BankgarantieFinancienOpsplitsenViewModel : ValidationBase<BankgarantieFinancienOpsplitsenViewModel>
{
...
public BankgarantieFinancienOpsplitsenViewModel(BankgarantieFinancienState state, ...)
{
...
Dossiernummer = state.Dossiernummer;
Kopers = state.Kopers.Select(k =>
{
var bfkvm = new BankgarantieFinancienKoperViewModel(k, adresService);
bfkvm.ObservePropertyChanged(koper => koper.Bedrag).Subscribe(p => CalculateOpenstaandBedrag());
return bfkvm;
}).ToList();
...
}
public string Dossiernummer
{
get { return _dossiernummer; }
private set
{
if (value == _dossiernummer) return;
_dossiernummer = value;
NotifyOfPropertyChange(() => Dossiernummer);
}
}
...
}
}
The relevant part of the View:
<Window x:Class="NatWa.MidOffice.Modules.Financien.Views.BankgarantieFinancienOpsplitsenView"
...>
<Grid Style="{StaticResource WindowPaddingStyle}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
...
</Grid.RowDefinitions>
...
<ItemsControl x:Name="Kopers" Grid.Row="1">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border BorderBrush="{StaticResource BorderBrush}" BorderThickness="1" Margin="0,3" Padding="5">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
...
<StackPanel Grid.Column="1" Orientation="Vertical">
...
<StackPanel Orientation="Horizontal" VerticalAlignment="Top" Margin="0,3" HorizontalAlignment="Right">
...
<!-- THIS IS WHERE I WANT TO DISPLAY THE DOSSIERNUMMER-PROPERTY OF THE PARENT VIEWMODEL -->
<TextBlock Text="{Binding ??Parent??.Dossiernummer}"/>
...
</StackPanel>
...
</StackPanel>
</Grid>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
...
</Grid>
</Window>
I did try to replace the TextBox with the following, based on this SO-answer, but to now result:
<TextBlock Text="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.Dossiernummer}"/>
I've also tried to add the DataContext binding to the Window (even though Caliburn.Micro should do this automatically):
<Window x:Class="NatWa.MidOffice.Modules.Financien.Views.BankgarantieFinancienOpsplitsenView"
...
DataContext="{Binding}">