我有一个带有列表框的WPF用户控件。我想通过绑定将列表框中的选定项传递给调用控件。我怎样才能做到这一点?
答案 0 :(得分:1)
您可以在用户控件上公开SelectedItem的新属性,并将其绑定到子控件ListBox。
用户控件的代码(我从Control继承):
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:
<ListBox
SelectedItem="{Binding RelativeSource={RelativeSource AncestorLevel=1, AncestorType={x:Type local:CustomListControl},Mode=FindAncestor},Path=SelectedItem, Mode=TwoWay}"
</ListBox>