【问题标题】:Bind IsSelected Property of ListBoxItem in ListBox with Multiple selection mode多选模式绑定ListBox中ListBoxItem的IsSelected属性
【发布时间】:2013-06-19 06:43:31
【问题描述】:

在 WinRT 应用程序 (C#) 中,我有 List<Item> items,它绑定到 ListBox。
Class Item 有 2 个字段:string Name 和 bool IsSelected。如您所知,我想将 IsSelected 字段绑定到 ListBoxItem 的 IsSelected 属性。

为什么我需要这个?为什么我没有使用 ListBox 的 SelectedItems 属性?

  1. ListBox刚刚加载的时候,我已经有一些Items,一定是IsSelected = true
  2. 我不想创建另一个集合来存储所有选定的项目。

我在寻找什么?
我正在寻找优雅的解决方案,例如在 WPF 中:

 <ListBox.ItemContainerStyle>
  <Style TargetType="ListBoxItem">
    <Setter Property="IsSelected" Value="{Binding IsSelected}"/>
  </Style>
 </ListBox.ItemContainerStyle>

但我们都知道,WinRT 根本不支持 setter 中的绑定。

我还在Filip Skakun 博客中查看nice post - 这是一种解决方案,但我需要自己写一些BindingBuilder/BindingHelper。

现在,我知道两种方法可以解决我的问题:

  1. 绑定ListBox 的SelectedItems 属性并存储另一个项目集合。 - 我不喜欢这种方式
  2. 像 Filip Skakun 那样做 - 如果我什么都没找到,我会使用它。

在理想情况下,我想为此使用本机解决方案,或者可能有人已经为我的情况编写/测试了嵌套 BindingBuilder - 这也会有帮助。

【问题讨论】:

    标签: c# xaml windows-8 windows-runtime


    【解决方案1】:

    如何创建一个派生的 ListBox:

    public class MyListBox : ListBox
    {
        protected override void PrepareContainerForItemOverride(
            DependencyObject element, object item)
        {
            base.PrepareContainerForItemOverride(element, item);
    
            if (item is Item)
            {
                var binding = new Binding
                {
                    Source = item,
                    Path = new PropertyPath("IsSelected"),
                    Mode = BindingMode.TwoWay
                };
    
                ((ListBoxItem)element).SetBinding(ListBoxItem.IsSelectedProperty, binding);
            }
        }
    }
    

    【讨论】:

    • 由于Item 是ListBox 上ItemSource 属性的类型,您可以删除if 语句以使控件更通用。实际上,我不确定为什么首先要进行检查。在我看来,检查element 是否为ListBoxItem 会更有意义。
    • @Trisped 呃,不。 ItemsSource 属性的类型是 object(或 WPF 中的 IEnumerable)。您通常分配一个仍然可以包含任何类型的集合,而不仅仅是应用程序定义的Item 类。另一方面,在 ListBox 中,元素类型始终为 ListBoxItem,除非您还覆盖 GetContainerForItemOverride 并返回其他类型。我建议从这里开始阅读:WPF ItemsControl.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多