在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>
感謝。很顯然,我一直在尋找太複雜的解決方案。 – ms10