2009-12-09 37 views
17

Tôi có một điều khiển WPF ListBox và tôi đang đặt ItemsSource của mình thành một tập hợp các đối tượng mục. Làm thế nào tôi có thể ràng buộc các tài sản IsSelected của ListBoxItem đến một tài sản Selected của một đối tượng mục tương ứng mà không cần phải có một thể hiện của đối tượng để đặt làm Binding.Source?Ràng buộc thuộc tính IsSelected của ListBoxItem vào một thuộc tính trên đối tượng từ nguồn của nó

Trả lời

34

Chỉ cần ghi đè ItemContainerStyle:

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

Oh, bằng cách này, tôi nghĩ rằng bạn muốn điều này tuyệt vời từ dr.WPF: ItemsControl: A to Z.

Hy vọng điều này sẽ hữu ích.

+1

Đây chính xác là những gì tôi đang tìm kiếm. Cảm ơn. – BrandonS

+2

Đáng buồn thay, điều này không làm việc với WinRT vì [các ràng buộc không được hỗ trợ trên Setters] (http://stackoverflow.com/a/11869065/641833). – Trisped

2

Tôi đang tìm một giải pháp trong mã, vì vậy đây là bản dịch của điều đó.

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

Xin chào BrandonS, Có thể cả hai giải pháp đều hoạt động tốt, tuy nhiên khi có thể, vui lòng sử dụng cách tiếp cận khai báo xml để xác định hành vi giao diện người dùng. Bằng cách đó nhiều người hơn (tương tác devs, vv) có thể hiểu nó và sửa đổi nó một cách dễ dàng. Trân trọng, – wacdany

Các vấn đề liên quan