简体   繁体   中英

Listbox SelectedItem binding to UserControl

I want to bind a ListBox SelectedItem to

This is my code for Listbox in my UserControl.xaml

Style x:Key="listbox" TargetType="ListBox">
        <!--  Region Setter Properties  -->
        <Setter Property="SelectionMode" Value="Single" />
        <Setter Property="ItemsSource" Value="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type program:UserControl}}, Path=Source}" />

`<ListBox Name="ListBox"
             Grid.Row="1"
             SelectedIndex="{Binding RelativeSource={RelativeSource FindAncestor,
                                                                    AncestorType={x:Type program:UserControl}},
                                     Path=SelectedIndex}"
             SelectedItem="{Binding Path=(program:UserControl.SelectedItem),
                                    RelativeSource={RelativeSource AncestorType={x:Type program:UserControl}}}"
             Style="{DynamicResource listbox}" />`

In my UserControl.xaml.cs

public object SelectedItem
    {
        get { return (object) GetValue(SelectedItemProperty); }
        set { SetValue(SelectedItemProperty, value); }
    }

    public int SelectedIndex    
    {
        get { return (int) GetValue(SelectedIndexProperty); }
        set { SetValue(SelectedIndexProperty, value); }
    }

    /// <summary>
    /// Identifies the <see cref="Selected" /> dependency property.
    /// </summary>
    public static readonly DependencyProperty SelectedProperty = DependencyProperty.Register(
        SelectedPropertyName,
        typeof(object),
        typeof(TileContainer),
        new UIPropertyMetadata(default(object)));

    public static readonly DependencyProperty SelectedItemProperty = DependencyProperty.Register("SelectedItem", typeof (object), typeof (UserControl), new PropertyMetadata(default(object)));
    public static readonly DependencyProperty SelectedIndexProperty = DependencyProperty.Register("SelectedIndex", typeof (int), typeof (UserControl), new PropertyMetadata(default(int)));

Normally it works, infact ItemsSource of my ListBox is correctly taken but SelectedIndex and SelectedItem don't work. I looked around the net but i didn't find any solution because maybe they don't have this issue.

I'm compiling with .NET 4.5 .

Thanx!

Update you DependencyProperty like so

public static readonly DependencyProperty SelectedProperty = DependencyProperty.Register(
    SelectedPropertyName,
    typeof(object),
    typeof(TileContainer),
    new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM