2009-12-09 8 views
17

WPF ListBoxコントロールがあり、アイテムオブジェクトのコレクションにItemsSourceを設定しています。 ListBoxItemIsSelectedプロパティを、Binding.Sourceとして設定するオブジェクトのインスタンスを持たずに、対応するアイテムオブジェクトのSelectedプロパティにバインドするにはどうすればよいですか?ListBoxItemのIsSelectedプロパティを、そのオブジェクトの元のオブジェクトのプロパティにバインドします。

答えて

34

だけItemContainerStyleを上書き:ItemsControl: A to Z

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

ああ、ところで、私はあなたがdr.WPFからこの素晴らしい記事をみたいと思います。

これが役に立ちます。

+1

これは私が探していたものです。ありがとう。 – BrandonS

+2

悲しいことに、[バインダーはセッターでサポートされていないので]これはWinRTでは機能しません(http://stackoverflow.com/a/11869065/641833)。 – Trisped

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の動作を定義することをお勧めします。そうすれば、より多くの人(インタラクション開発者など)がそれを理解して簡単に変更できます。 よろしく、 – wacdany