0
votes

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
Does this answer your question? Access parent DataContext from DataTemplateStayOnTarget

1 Answers

5
votes

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}}"