I have a WPF ListBox in Extended SelectionMode.
What I need to do is bind the ListBox to an observable collection of a data item class, which is easy, but essentially, bind the IsSelected
status of each ListBoxItem to a boolean property in the respective data item.
And, I need it to be two-way, so that I can populate the ListBox with selected and unselected items from the ViewModel.
I've looked at a number of implementations but none work for me. They include:
I realise this can be done in code-behind with an event handler, but given the complexity of the domain it would be horribly messy. I'd rather stick to two-way Binding with the ViewModel.
Thanks. Mark
In WPF you can easily bind your ListBox to a collection of items with a boolean property for the IsSelected state. If your question is about Silverlight, i'm afraid it won't work the easy way.
public class Item : INotifyPropertyChanged
{
// INotifyPropertyChanged stuff not shown here for brevity
public string ItemText { get; set; }
public bool IsItemSelected { get; set; }
}
public class ViewModel : INotifyPropertyChanged
{
public ViewModel()
{
Items = new ObservableCollection<Item>();
}
// INotifyPropertyChanged stuff not shown here for brevity
public ObservableCollection<Item> Items { get; set; }
}
<ListBox ItemsSource="{Binding Items, Source={StaticResource ViewModel}}"
SelectionMode="Extended">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="IsSelected" Value="{Binding IsItemSelected}"/>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding ItemText}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With