2009-12-09 14 views

Respuesta

34

Sólo anulan ItemContainerStyle:

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

Ah, por cierto, creo que desea esta maravillosa artículos de dr.WPF: ItemsControl: A to Z.

Espero que esto ayude.

+1

Esto es exactamente lo que estaba buscando. Gracias. – BrandonS

+2

Lamentablemente, esto no funciona con WinRT ya que [los enlaces no son compatibles con Setters] (http://stackoverflow.com/a/11869065/641833). – Trisped

2

Estaba buscando una solución en el código, así que aquí está la traducción de eso.

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

Hola BrandonS, Quizás ambas soluciones funcionen bien; sin embargo, cuando sea posible, prefiera el enfoque declarativo xml para definir comportamientos de IU. De esta forma, más personas (desarrolladores de interacción, etc.) pueden entenderlo y modificarlo fácilmente. Saludos, – wacdany

Cuestiones relacionadas