2012-11-28 29 views
4

我有一個WPF列表框在Extended SelectionMode中。如何將ListBoxItem.IsSelected綁定到布爾數據屬性

我需要做的是將ListBox綁定到數據項類的可觀察集合,這很容易,但實質上,將每個ListBoxItem的IsSelected狀態綁定到相應數據項中的布爾屬性。

而且,我需要它是雙向的,以便我可以使用ViewModel中的選定和未選定的項目填充ListBox。

我看了一些實現,但沒有爲我工作。它們包括:

  • 添加DataTrigger到ListBoxItem中的風格和調用狀態動作變化

我明白,這可以在後臺代碼來完成與事件處理程序,但考慮到該域的複雜性這將是可怕的混亂。我寧願堅持使用ViewModel進行雙向綁定。

謝謝。 Mark

回答

10

在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> 
+0

感謝。很顯然,我一直在尋找太複雜的解決方案。 – ms10

相關問題