2009-12-09 92 views

回答

34

只是覆蓋ItemContainerStyle:

<ListBox ItemsSource="..."> 
    <ListBox.ItemContainerStyle> 
     <Style TargetType="{x:Type ListBoxItem}"> 
     <Setter Property="IsSelected" Value="{Binding Selected}"/> 
     </Style> 
    </ListBox.ItemContainerStyle> 
    </ListBox> 

哦,順便說一句,我想你想從dr.WPF這美妙的文章:ItemsControl: A to Z

希望這會有所幫助。

+1

這正是我所期待的。謝謝。 – BrandonS 2009-12-09 18:20:11

+2

由於[Setters不支持綁定](http://stackoverflow.com/a/11869065/641833),因此可惜這不適用於WinRT。 – Trisped 2014-05-15 19:50:10

2

我正在尋找代碼解決方案,所以這裏是翻譯。

System.Windows.Controls.ListBox innerListBox = new System.Windows.Controls.ListBox(); 

//The source is a collection of my item objects. 
innerListBox.ItemsSource = this.Manager.ItemManagers; 

//Create a binding that we will add to a setter 
System.Windows.Data.Binding binding = new System.Windows.Data.Binding(); 
//The path to the property on your object 
binding.Path = new System.Windows.PropertyPath("Selected"); 
//I was in need of two way binding 
binding.Mode = System.Windows.Data.BindingMode.TwoWay; 

//Create a setter that we will add to a style 
System.Windows.Setter setter = new System.Windows.Setter(); 
//The IsSelected DP is the property of interest on the ListBoxItem 
setter.Property = System.Windows.Controls.ListBoxItem.IsSelectedProperty; 
setter.Value = binding; 

//Create a style 
System.Windows.Style style = new System.Windows.Style(); 
style.TargetType = typeof(System.Windows.Controls.ListBoxItem); 
style.Setters.Add(setter); 

//Overwrite the current ItemContainerStyle of the ListBox with the new style 
innerListBox.ItemContainerStyle = style; 
+3

Hello BrandonS, 也許這兩種解決方案都能正常工作,但是如果可能的話,請使用xml聲明式方法來定義UI行爲。這樣,更多的人(Interaction devs等)可以理解並輕鬆修改它。 關心, – wacdany 2012-07-09 14:41:07

相關問題