将 WPF 用户控件选择传递给宿主控件 [英] Passing WPF user control selection to host control
本文介绍了将 WPF 用户控件选择传递给宿主控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有列表框的 WPF 用户控件.我想通过绑定将列表框中的选定项传递给调用控件.我怎样才能做到这一点?
I have a WPF user control with a list box. I want to pass the selected item in the list box to the calling control through binding. How can I achieve this?
推荐答案
您可以在用户控件上为 SelectedItem 公开一个新属性,并将其绑定到子控件 ListBox.
You can expose a new property for SelectedItem on your user control and bind it to the child control ListBox.
您的用户控件的代码(虽然我是从 Control 继承的):
Code for your user control (I inherited from Control though):
public class CustomListControl : Control
{
static CustomListControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomListControl), new FrameworkPropertyMetadata(typeof(CustomListControl)));
SelectedItemProperty = ListBox.SelectedItemProperty.AddOwner(typeof(CustomListControl));
}
public static readonly DependencyProperty SelectedItemProperty;
public Object SelectedItem
{
get { return this.GetValue(SelectedItemProperty); }
set { this.SetValue(SelectedItemProperty, value); }
}
}
并将来自内部 ListBox 的绑定添加到 Generic.xaml 标记中的 UserControl:
And add the binding from the inner ListBox to your UserControl in the Generic.xaml markup:
<ListBox
SelectedItem="{Binding RelativeSource={RelativeSource AncestorLevel=1, AncestorType={x:Type local:CustomListControl},Mode=FindAncestor},Path=SelectedItem, Mode=TwoWay}"
</ListBox>
这篇关于将 WPF 用户控件选择传递给宿主控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文