2

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.

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

  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.

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>

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

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. 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.

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.

4

1 回答 1

2

如何创建一个派生的 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);
        }
    }
}
于 2013-06-19T17:55:14.887 回答