C# 什么';这两种声明自绑定的方式有什么区别?

C# 什么';这两种声明自绑定的方式有什么区别?,c#,.net,wpf,binding,C#,.net,Wpf,Binding,我有一个UserControl,其中包含必须绑定到内部控件的ItemsSource属性的ItemsSource DependencyProperty: ItemsSource="{Binding ItemsSource, RelativeSource={RelativeSource Self}}" vs controlName是控件的名称 第一个绑定不起作用,而第二个绑定起作用。我不明白有什么不同 有什么想法吗 编辑: XAML: 这不起作用--> 这是有效的--> 如果要绑定到父用户控件的

我有一个UserControl,其中包含必须绑定到内部控件的ItemsSource属性的ItemsSource DependencyProperty:

ItemsSource="{Binding ItemsSource, RelativeSource={RelativeSource Self}}"
vs

controlName是控件的名称

第一个绑定不起作用,而第二个绑定起作用。我不明白有什么不同

有什么想法吗

编辑:

XAML:


这不起作用-->
这是有效的-->

如果要绑定到父用户控件的DP,则需要使用
Mode=FindAncestor
绑定它。由于您绑定的是内部控制,因此需要沿着可视化树向上移动

Self模式
将在内部控制而不是父用户控制中搜索DP

ItemsSource="{Binding ItemsSource, RelativeSource={RelativeSource FindAncestor, 
                                                   AncestorType=UserControl}}"

我根据你的问题假设你有一个Xaml,它的结构如下:

<UserControl x:Name="rootElement">
    <ListBox ItemsSource="{Binding .....}" />
</UserControl>
。。。这将在声明绑定的控件(即
列表框
)上查找属性
itemsource
。在您的情况下,这将导致一个问题,因为您实际上正在设置一个无限递归:您的
ItemsSource
绑定到
ItemsSource
绑定到。。。无限的。您在这里提到您正在使用
UserControl
,我怀疑您可能期望
RelativeSource
返回根
UserControl
元素,但事实并非如此

ItemsSource="{Binding ItemsSource, ElementName=rootElement}"
。。。这将绑定到控件上具有特定名称的属性
ItemsSource
。如果您在
UserControl
中工作,则通常会在
UserControl
的根元素上设置
x:Name
,并以这种方式从绑定中引用它。这将允许您将子
列表框
绑定到
用户控件
的公共
项资源
属性

仅供参考,另一种选择是使用
AncestorType
绑定来查找父级
UserControl
。如果您的
UserControl
类型被称为
MyControl
,则其外观如下:

ItemsSource="{Binding ItemsSource, RelativeSource={RelativeSource FindAncestor, AncestorType=MyControl}}"

“controlName”是您的UserControl的名称吗?更新了答案。你能试试吗?现在我明白了,Self指的是树视图本身,而不是它的父级。谢谢,我遇到的问题是,当我使用Self时,我认为Self是容器控件,而不是设置绑定的控件。谢谢你的帮助。
ItemsSource="{Binding ItemsSource, RelativeSource={RelativeSource Self}}"
ItemsSource="{Binding ItemsSource, ElementName=rootElement}"
ItemsSource="{Binding ItemsSource, RelativeSource={RelativeSource FindAncestor, AncestorType=MyControl}}"