问题
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:
- Adding a DataTrigger to the ListBoxItem's style and calling a state action change
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
回答1:
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>
来源:https://stackoverflow.com/questions/13611113/how-to-bind-listboxitem-isselected-to-boolean-data-property