WPF。在运行时访问绑定集合

时间:2019-03-19 13:00:00

标签: wpf data-binding

我有一个wpf窗口,其中某些控件绑定到了不同的集合。

<controls:CustomTextBox ItemsSource="{Binding Countries}" />
<controls:CustomTextBox ItemsSource="{Binding Localities}" />

“ ItemsSource”是用于与集合链接的自定义DependencyProperty。 我想在运行时通过PreviewLostKeyboardFocus获取集合,以验证集合中是否存在文本。

PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
    CustomTextBox textBox = (CustomTextBox)sender;
    var bindingExpression = textBox.GetBindingExpression(textBox.ItemsSourceDependencyProperty);
    ...
}

我得到bindingExpression,但是我不知道如何在Collection中查找文本。 谢谢。

1 个答案:

答案 0 :(得分:0)

为什么不直接访问CLR包装的依赖项属性?

CustomTextBox textBox = (CustomTextBox)sender;
var collection = textBox.ItemsSource;

为了能够在集合中“查找文本”,您可能必须将其强制转换为适当的类型,例如IEnumerable<string>或任何类型的Countries或{{1 }}是;

Localities