开发者

Passing WPF user control selection to host control

开发者 https://www.devze.com 2023-01-07 00:03 出处:网络
I have a WPF user control with a list box. I want t开发者_如何转开发o pass the selected item in the list box to the calling control through binding. How can I achieve this?You can expose a new propert

I have a WPF user control with a list box. I want t开发者_如何转开发o pass the selected item in the list box to the calling control through binding. How can I achieve this?


You can expose a new property for SelectedItem on your user control and bind it to the child control ListBox.

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); }
    }
}

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>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号