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.

ASh
  • 34,632
  • 9
  • 60
  • 82
Cgt
  • 23
  • 1
  • 4
  • Does this answer your question? [Access parent DataContext from DataTemplate](https://stackoverflow.com/questions/3404707/access-parent-datacontext-from-datatemplate) – StayOnTarget Mar 03 '21 at 14:03

1 Answers1

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}}"
StayOnTarget
  • 11,743
  • 10
  • 52
  • 81
ASh
  • 34,632
  • 9
  • 60
  • 82
  • 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? – Cgt Apr 16 '16 at 18:42
  • @Cgt, take a look here: http://stackoverflow.com/questions/15982834/tutorial-on-advanced-xaml-databinding and http://stackoverflow.com/questions/3456677/concepts-of-visul-tree-and-logical-tree – ASh Apr 16 '16 at 18:54