在 WPF 中,您可以轻松地将 ListBox 绑定到具有 IsSelected 状态的布尔属性的项目集合。如果您的问题是关于 Silverlight 的,恐怕它不会那么简单。
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>