istBoxItem中的绑定IsSelected属性列表框中具有

istBoxItem中的绑定IsSelected属性列表框中具有

本文介绍了ListBoxItem中的绑定IsSelected属性列表框中具有多个选择模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在WinRT的应用程序(C#)我有列表<项目>项目,其结合的ListBox 。结果
类项目有2场:字符串名称布尔IsSelected 。正如你已经了解,我想 IsSelected 字段绑定到一个ListBoxItem的IsSelected属性。结果

In WinRT App (C#) I have List<Item> items, which bind to ListBox.
Class Item has 2 fields: string Name and bool IsSelected. As you already understood, I want to bind IsSelected field to IsSelected Property of ListBoxItem.

为什么我需要这个?为什么我没有用我的的ListBox ?结果

Why I need this? Why I didn't use SelectedItems property of my ListBox?


  1. 的ListBox 刚装的,我已经有一些项目,它必须是 IsSelected = true的

  2. 我不想再创建一个集合来存储所有选定的项目。

  1. When ListBox just loaded, I already have some Items, which must be IsSelected = true
  2. I don't want to create another collection to store all selected items.

我在找什么结果
我在WPF寻找优雅的解决方案,如:

What I'm looking for?
I'm looking for elegant solution, like in WPF:

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



但我们都知道,WinRT中不支持绑定的制定者都没有。结果

But we all know, that WinRT doesn't support bindings in setters at all.

我也查的在博客 - 这是解决方案之一,但我需要我自己写的一些 BindingBuilder / BindingHelper

I also check nice post in Filip Skakun blog - and this is one of solution, but I need to write some of the BindingBuilder/BindingHelper by my self.

而现在,我知道要解决我的问题,有两种方式:

And now, I know two way to solve my problem:


  1. 绑定 SelectedItems 属性的的ListBox 和存储项目的另一个集合。 - 我不喜欢这种方式

  2. 请像 - 如果我发现什么我用这个。

  1. Bind SelectedItems property of ListBox and store another collection of items. - I do not like this way
  2. Do it like Filip Skakun - if I find nothing I use this.

在理想的情况下,我想用这个原生解决方案,或者也许有人已经写/测试嵌套的 BindingBuilder 我的情况 - 这是会有所帮助过

In ideal situation I want to use native solution for this, or maybe someone already wrote/tested nested BindingBuilder for my situation - it's will be helpful too.

推荐答案

如何创建派生列表框:

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

这篇关于ListBoxItem中的绑定IsSelected属性列表框中具有多个选择模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 21:30