2012-11-14 143 views
2

我具有包含的ItemsSource DependenceProperty必须被绑定到一个内部控制的ItemsSource属性的用户控件:这两种声明自绑定的方式有什么区别?

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

VS

ItemsSource="{Binding ItemsSource, ElementName=controlName}" 

控件名称是控件的名称。

第一个绑定不工作,而第二个工作。我没有区别。

任何想法?

编辑:

XAML:

<UserControl x:Class="MultiSelectTreeView.MultiSelectableTreeView" 

     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 

     mc:Ignorable="d" 

     Name="multiTree" > 

This does not work ---> <TreeView ItemsSource="{Binding ItemsSource, RelativeSource={RelativeSource Self}}" > 
This works ---> <TreeView ItemsSource="{Binding ItemsSource, ElementName=multiTree}" > 
+0

是您的用户控件的“controlName'叫什么名字? –

+0

@ RV1987:是的。 –

+0

更新了答案。你可以试试吗? –

回答

1

在要绑定于母公司UserControl的DP的情况下,您需要使用Mode = FindAncestor绑定它。由于您对内部控制有约束力,因此您需要沿着可视化树行进。

Self Mode将在内部控件中搜索DP,而不是在父级UserControl中搜索。

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

现在我明白了,Self指的是TreeView本身,而不是它的父代。 –

+0

是的...... –

1

我从你的问题假设你拥有的XAML是这样的结构:然后

<UserControl x:Name="rootElement"> 
    <ListBox ItemsSource="{Binding .....}" /> 
</UserControl> 

你绑定在执行以下操作:

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

.. 。这将查找声明绑定的控件上的属性ItemsSource(即,ListBox)。在你的情况下,这将导致一个问题,因为你基本上设置了一个无限递归:你的ItemsSource绑定到ItemsSource绑定到...无限。你提到你在这里使用UserControl,我怀疑你可能期望RelativeSource返回根UserControl元素 - 但事实并非如此。

ItemsSource="{Binding ItemsSource, ElementName=rootElement}" 

...这将绑定到财产ItemsSource上具有特定名称的控制。如果您在UserControl中工作,那么通常您会在UserControl的根元素上设置x:Name,并且将以这种方式从绑定中引用它。这将允许您将子女ListBox绑定到您的UserControl的公共ItemsSource财产。

仅供参考,另一种替代方法是使用AncestorType绑定来查找您的父母UserControl。如果您UserControl类型称为MyControl,它会是这个样子:

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

谢谢,我遇到的问题是,当我使用Self时,我认为Self是容器控件,而不是绑定被设置的控件。谢谢你的帮助。 –

相关问题