Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从ItemsControl绑定到父DataTemplate属性_C#_Wpf_Xaml_Mvvm_Data Binding - Fatal编程技术网

C# 从ItemsControl绑定到父DataTemplate属性

C# 从ItemsControl绑定到父DataTemplate属性,c#,wpf,xaml,mvvm,data-binding,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 ItemsSourc

假设我有这个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>
类MyViewModel
{
public MyStringValue{get;set;}=“HelloWorld”
公共IList ChildViewModels{get;set;}
}
我一直收到以下错误消息: “找不到引用为'RelativeSource FindAncestor'的绑定源…”
因此,基本上,我正在尝试绑定ItemsControl的父属性容器,但似乎无法绑定。

AncestorType
属于更高级别的可视化树(
ItemsControl
此处)

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


RelativeSource
AncestorType
是属于更高级别的可视化树(
ItemsControl
此处)

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


哇,就这么多?我对wpf可视化树的概念还很陌生,我已经试了几个小时让它工作。谢谢!谢谢@Ash!有什么好的教程可以让我在视觉树级别上阅读,以及绑定是如何工作的吗?@Cgt,看看这里:哇,就这些?我对wpf可视化树的概念还很陌生,我已经试了几个小时让它工作。谢谢!谢谢@Ash!有什么好的教程可以让我在视觉树级别阅读,以及绑定是如何工作的吗?@Cgt,看看这里:这是否回答了你的问题?这回答了你的问题吗?
{Binding Path=DataContext.MyStringValue, 
         RelativeSource={RelativeSource AncestorType=ItemsControl}}"