2

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.

1

1 Answer 1

9

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}}" 
Sign up to request clarification or add additional context in comments.

2 Comments

wow, that's all it took? I am still new to wpf visual tree concept, and I have tried for hours to get it to work. Thanks a lot! Thanks @Ash! Is there any good tutorial on where I can read up on the visual tree level and how binding works?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.