c# - 从 ItemsControl 绑定(bind)到父 DataTemplate 属性

标签 c# wpf xaml mvvm data-binding

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

相关文章:

c# - TextBoxFor() 不生成验证标记

c# - 使用长行标记增强 WPF 文本框?

c# - StackPanel 可见性取决于 Combobox 选择

c# - 如何在C#中使用zKemKeeper连接考勤机?

c# - FakeItEasy:从返回 null 的 protected 方法获取参数

c# - 要构造的自动映射器类

c# - 在 WPF 中更改按钮图像的更好算法

wpf - 在 Control 或 UIElement 上找到应用的 ScaleTransform?

基于绑定(bind)数据类型的WPF弹出选择模板

c# - 我如何在 silverlight 中将 Xaml 转换为 Rtf?