假设我有这个 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 ... 绑定(bind)的源...” 所以基本上,我正在尝试绑定(bind) ItemsControl 的父属性容器,但似乎我不能。
最佳答案
RelativeSource
AncestorType
属于更高级别的可视化树(此处为ItemsControl
)。
由于 MyStringValue
不是 ItemsControl
的属性,您应该更改 Binding
Path
以指向 View 模型(DataContext
):
{Binding Path=DataContext.MyStringValue,
RelativeSource={RelativeSource AncestorType=ItemsControl}}"
关于c# - 从 ItemsControl 绑定(bind)到父 DataTemplate 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36667969/