在UserControl中公开ComboBox的ItemsSource [英] Exposing ItemsSource of a ComboBox within a UserControl
问题描述
我创建了一个UserControl,其中包含一个我想要公开的ComboBox,因此当我添加UserControl时,我可以从MainWindow.xaml中绑定到ComboBox。我发现下面的代码有效,但我不明白为什么/实际发生了什么。
I created a UserControl which has a ComboBox within it that I would like to expose so I can bind to the ComboBox from within the MainWindow.xaml when I add the UserControl. I found the below code, which works, but I don't understand why/what is actually going on.
<ComboBox HorizontalAlignment="Left" Margin="38,2,0,0" VerticalAlignment="Top" Width="120" ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Views:UserControl1, AncestorLevel=1}, Path=ComboBox1ItemsSource}" />
* *(Views)是我的Views目录的XAML定义的命名空间。
虽然我可以将ItemsSource设置为:
**(Views) is a XAML defined namespace to my Views directory.
I would've though I could have just set the ItemsSource to:
ItemsSource = "{Binding RelativeSource={RelativeSource Self}, Path=ComboBox1ItemsSource}"
为什么不将源设置为自我工作?使用FindAcestor时发生了什么,如上面第一段代码所示。
如果它很重要,我必须添加以下代码第一部分代码可以工作。
Why wouldn't setting the source to Self work? What is going on when the using the FindAcestor as shown in the first bit of code above.
Also in case it is important, I did have to add the following code behind for the first bit of code to work.
public static readonly DependencyProperty ComboBox1ItemsSourceProperty;
public IEnumerable ComboBox1ItemsSource { get; set; }
static UserControl1()
{
ComboBox1ItemsSourceProperty = DependencyProperty.Register("ComboBox1ItemsSource", typeof(IEnumerable), typeof(UserControl1));
}
推荐答案
使用RelativeSource
告诉绑定忽略当前DataContext
,并尝试在特定元素上查找指定的属性。
设置{RelativeSource Self}
会尝试在ComboBox
上找到名为ComboBox1ItemsSource
的属性本身。由于ComboBox
没有具有该名称的属性,绑定将失败。
使用{RelativeSource FindAncestor,...}
走上逻辑树,找到最近的UserControl1
,并尝试使用来自该实例的ComboBox1ItemsSource
属性。
关于 RelativeSource标记扩展的MSDN文档 [ ^ ]对各种选项有不错的解释。
UsingRelativeSource
tells the binding to ignore the currentDataContext
, and try to find the specified property on a particular element instead.
Setting{RelativeSource Self}
would attempt to find a property calledComboBox1ItemsSource
on theComboBox
itself. Since theComboBox
doesn't have a property with that name, the binding would fail.
Using{RelativeSource FindAncestor, ...}
walks up the logical tree to find the nearestUserControl1
, and tries to use theComboBox1ItemsSource
property from that instance.
The remarks on the MSDN documentation for the RelativeSource markup extension[^] have a decent explanation of the various options.
这篇关于在UserControl中公开ComboBox的ItemsSource的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!