2009-12-09 6 views

Antwort

34

Nur ItemContainerStyle außer Kraft setzen:

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

Oh, übrigens, ich glaube, Sie diese wunderbare Artikel von dr.WPF möchten: ItemsControl: A to Z.

Hoffe, das hilft.

+1

Dies ist genau das, was ich gesucht habe. Vielen Dank. – BrandonS

+2

Leider funktioniert dies nicht mit WinRT, da [Bindungen auf Setter nicht unterstützt werden] (http://stackoverflow.com/a/11869065/641833). – Trisped

2

Ich war auf der Suche nach einer Lösung im Code, also hier ist die Übersetzung davon.

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

Hallo BrandonS, Vielleicht funktionieren beide Lösungen gut, aber wenn möglich, bevorzugen Sie XML deklarativen Ansatz, um UI-Verhalten zu definieren. Auf diese Weise können mehr Leute (Interaktionsentwickler usw.) es verstehen und leicht modifizieren. Grüße, – wacdany

Verwandte Themen