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.

Community
  • 1
  • 1
jimpanzer
  • 3,470
  • 4
  • 44
  • 84

1 Answers1

2

How about creating a derived 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);
        }
    }
}
Clemens
  • 123,504
  • 12
  • 155
  • 268
  • Since `Item` is the type of the ItemSource property on the `ListBox` you could remove the if statement to make the control more generic. Actually I am not sure why that check is there in the first place. It would make more sense in my mind to check if `element` is a `ListBoxItem`. – Trisped May 16 '14 at 17:51
  • @Trisped Uh, no. The type of the `ItemsSource` property is `object` (or `IEnumerable` in WPF). You typically assign a collection which could still contain any type, not just an application-defined `Item` class. On the other hand, in a ListBox the element type is always `ListBoxItem` unless you also override `GetContainerForItemOverride` and return some other type. I'd recommend to start reading here: [WPF ItemsControl](http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.aspx). – Clemens May 16 '14 at 19:18