繁体   English   中英

列表框SelectedItem绑定到UserControl

[英]Listbox SelectedItem binding to UserControl

我想将一个ListBox SelectedItem绑定到

这是我的UserControl.xaml中的Listbox代码

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}" />`

在我的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)));

通常它可以正常工作,我的ListBox的事实上的ItemsSource可以正确使用,但是SelectedIndex和SelectedItem不起作用。 我环顾四周,但找不到任何解决方案,因为也许他们没有这个问题。

我正在使用.NET 4.5进行编译。

感谢名单!

像这样更新您的DependencyProperty

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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