【问题标题】:Listbox SelectedItem binding to UserControl列表框 SelectedItem 绑定到 UserControl
【发布时间】:2015-07-23 15:17:41
【问题描述】:

我想将 ListBox SelectedItem 绑定到

这是我的 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}" />`

在我的 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 进行编译。

谢谢!

【问题讨论】:

  • 您需要添加 Mode = TwoWay 以便将值从目标设置回源(您的属性)
  • 我做了,但它不起作用。

标签: c# wpf xaml binding listbox


【解决方案1】:

像这样更新你的 DependencyProperty

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-02
    • 1970-01-01
    • 2012-05-24
    • 2011-02-16
    • 1970-01-01
    • 2011-02-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多