【问题标题】:Binding to Parent DataTemplate Property from ItemsControl从 ItemsControl 绑定到父 DataTemplate 属性
【发布时间】:2016-04-16 18:21:15
【问题描述】:

假设我有这个 ViewModel 和 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>

我不断收到此错误消息: “找不到与参考'RelativeSource FindAncestor ...”绑定的源 所以基本上,我正在尝试绑定 ItemsControl 的 parents 属性容器,似乎我不能。

【问题讨论】:

标签: c# wpf xaml mvvm data-binding


【解决方案1】:

RelativeSource AncestorType 属于更高层次的视觉树(ItemsControl 这里)。

由于MyStringValue 不是ItemsControl 的属性,您应该更改Binding Path 以及指向视图模型(DataContext):

{Binding Path=DataContext.MyStringValue, 
         RelativeSource={RelativeSource AncestorType=ItemsControl}}"

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2014-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多