Ignacio Soler Garcia
Ignacio Soler Garcia

Reputation: 21855

How to bind IsSelected ListboxItem property in a windows phone application?

In WPF I used to do this:

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

This is not working on a Windows Phone 8 application as I'm getting an expection saying that the property is readonly.

How should I do this simple task?

Thanks.

Upvotes: 1

Views: 495

Answers (1)

Alaa Masoud
Alaa Masoud

Reputation: 7135

I came through this issue before, it seems like binding through property setters isn't supported. However, there is a workaround. You can subclass ListBox and override PrepareContainerForItemOverride. This method is invoked on each item that needs to be added to the list which makes it a perfect place to set your binding there. You won't need to anything special to your Xaml in that case

public class ListBoxEx : ListBox {
  protected override void PrepareContainerForItemOverride(System.Windows.DependencyObject element, object item) {
    base.PrepareContainerForItemOverride(element, item);
    ((ListBoxItem)element).IsSelected = ((MyModel)item).IsSelected;
  }
}
<local:ListBoxEx>
  <local:ListBoxEx.ItemTemplate>
    <DataTemplate>
      <!-- Bind your properties as you would normally do -->
    </DataTemplate>
  </local:ListBoxEx.ItemTemplate>
</local:ListBoxEx>

Upvotes: 1

Related Questions