Reputation: 23
Say I have this ViewModel and xaml:
class MyViewModel
{
public MyStringValue {get;set;} = "HelloWorld"
public IList<CustomObject> ChildViewModels{get;set;}
}
<DataTemplate DataType="{x:Type local:MyViewModel}">
<ItemsControl ItemsSource="{Binding ChildViewModels}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding Path=MyStringValue,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType={x:Type local:MyViewModel}}}"/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</DataTemplate>
I keep getting this error message: "Cannot find source for binding with reference 'RelativeSource FindAncestor ... " So basically, I'm trying to bind the parents property container of ItemsControl and it seems like I can't.
Upvotes: 2
Views: 4295
Reputation: 35720
RelativeSource
AncestorType
is something which belongs to a higher level of visual tree (ItemsControl
here).
Since MyStringValue
is not a property of ItemsControl
, you should change Binding
Path
as well to point to view model (DataContext
):
{Binding Path=DataContext.MyStringValue,
RelativeSource={RelativeSource AncestorType=ItemsControl}}"
Upvotes: 9