0

I am using MVVM pattern with Silverlight 4 to bind a collection of TODO items to a ListBox.

There is a property IsSelected on each TODO entity. This allow for multiple selections to be made in the UI that are bound back to the ViewModel. At the same time any changes made by the ViewModel get reflected in the View.

I am basically trying to do what was suggested in this answer.

Unfortunately in Silverlight (as opposed to WPF) I just cannot find a way to do this with the template since Bindings in a Style Setter are not supported in SL4.

<ListBox.ItemContainerStyle>
    <Style TargetType="{x:Type ListBoxItem}">
        <Setter Property="IsSelected" 
                Value="{Binding Mode=TwoWay, Path=IsSelected}"/>
    </Style>
</ListBox.ItemContainerStyle>

However unlike any other method - this seems to be the most reliable for two way binding of a selected items list.

How can I express this binding in codebehind or XAML?

Community
  • 1
  • 1
Simon_Weaver
  • 140,023
  • 84
  • 646
  • 689

1 Answers1

3

The easiest way I know of is to overload the DataTemplate and make it look like a ListBoxItem selection. I used a DataStateBehavior from the Blend 4.0 Silverlight SDK to tie the IsSelected property to the correct look and feel.

<i:Interaction.Behaviors>
    <ei:DataStateBehavior Binding="{Binding IsSelected, Mode=TwoWay}" Value="True" TrueState="Selected" FalseState="Unselected"/>                   
</i:Interaction.Behaviors>

Rather than paste the entire thing, I'm linking to a post I added to my blog here.

WiredPrairie
  • 58,954
  • 17
  • 116
  • 143
  • +1 mate, I was just implementing something in exactly this way and your blog post helped me to confirm that it was going to work! ;) – Town Sep 02 '11 at 16:14
  • This doesn't appear to work correctly in WPF. Is this a WPF bug? For some reason the fill color does not appear on the Person(s) that are initially selected. The color doesn't appear until I manually uncheck and recheck the box. Verified it works in Silverlight. – kbeal2k Dec 05 '12 at 15:34
  • You shouldn't need this solution in WPF as stated by the original question. If you're having troubles, I'd suggest following the answer link in the question or posting a new question with details of what you're seeing. – WiredPrairie Dec 06 '12 at 11:42