我有一個WPF ListBox
控件,我將其ItemsSource
設置爲一組項目對象。如何將ListBoxItem
的IsSelected
屬性綁定到相應項目對象的Selected
屬性,而無需將該對象的實例設置爲Binding.Source
?將ListBoxItem的IsSelected屬性綁定到其源對象上的屬性
17
A
回答
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。
希望這會有所幫助。
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
相關問題
- 1. 綁定一個ListBoxItem的IsSelected屬性到的DataContext的ItemsSource
- 2. 如何將ListBoxItem的屬性綁定到已綁定到ListBox的ItemsSource的屬性
- 3. 綁定到對象屬性
- 4. 將c#屬性綁定到SAME控件上的其他屬性
- 5. Silverlight:綁定資源對象的屬性
- 6. 將控件屬性綁定到XAML中的對象屬性
- 7. 將控件的ID屬性綁定到對象屬性
- 8. WPF綁定到具有特定屬性的對象的屬性
- 9. wpf combobox - 綁定自定義isselected屬性
- 10. 綁定到ViewModel中的對象屬性
- 11. 綁定到對象的屬性
- 12. 對象屬性綁定庫
- 13. 如何將ListBox綁定到對象上List類型的屬性?
- 14. 如何將ItemTemplate CheckBox的Command屬性綁定到ViewModel對象的屬性?
- 15. 綁定到SelectedItem屬性的屬性
- 16. 綁定到屬性的屬性
- 17. WPF綁定到派生對象屬性
- 18. WPF簡單綁定到對象屬性
- 19. 如何將屬性綁定到來自QML的單例對象屬性
- 20. 僅將某些屬性綁定到grails域對象上?
- 21. 可以在MVVM樣式中使用MultiselectList(將其IsSelected屬性綁定到viewmodel)?
- 22. 將對象屬性綁定到特定的Telerik RadGridView列
- 23. 將IsSelected屬性添加到EF POCO
- 24. Ember對象中的Emberjs綁定屬性
- 25. 更新綁定到對象[屬性](Binding.IndexerName怪異)的綁定
- 26. ActionScript設置來自其他對象屬性的對象屬性?
- 27. WPF將usercontrol的屬性綁定到父級的屬性
- 28. Silverlight - 將按鈕上的IsEnabled屬性綁定到ViewModel上的屬性
- 29. 綁定屬性parent屬性
- 30. Knockoutjs VS屬性綁定到屬性()
這正是我所期待的。謝謝。 – BrandonS 2009-12-09 18:20:11
由於[Setters不支持綁定](http://stackoverflow.com/a/11869065/641833),因此可惜這不適用於WinRT。 – Trisped 2014-05-15 19:50:10