简体   繁体   English

WPF将值与复选框关联

[英]WPF associate value with checkbox

I am new to WPF and am having issues with associating a value with an object. 我是WPF的新手,在将值与对象关联时遇到问题。 I have a TreeView with CheckBoxes and I am wondering how I can associate an object to each checkbox. 我有一个带有CheckBoxes的TreeView,我想知道如何将一个对象关联到每个复选框。 I want to be able to select all the checked checkboxes (no problem) and get a list of objects that are associated with each checked box. 我希望能够选中所有选中的复选框(没问题),并获取与每个复选框相关联的对象的列表。

For example, let's say I have a class called Fruit that has properties DisplayName and Price 例如,假设我有一个名为Fruit的类,该类具有DisplayName和Price属性

TreeView: 树视图:

  • Mango 芒果
  • ✓ Apple ✓苹果
  • Orange 橙子

I want to be able to return the Apple object so that I can get the Price and other properties associated to the Fruit. 我希望能够返回Apple对象,以便获得Price和与Fruit关联的其他属性。

Here is a code sample for me adding checkboxes to the TreeView 这是我为TreeView添加复选框的代码示例

TreeViewItem treeViewItem = new TreeViewItem();

CheckBox chkBox = new CheckBox();
chkBox.IsChecked = false;
chkBox.Content = "Value";
chkBox.IsThreeState = false;
chkBox.Click += chkBox_Click;

treeViewItem.Header = chkBox;

TreeViewItem inherits from FrameworkElement which provides the Tag property for this very purpose. TreeViewItem继承自FrameworkElement,后者为此提供了Tag属性 You can set this property to an arbitrary object of your choosing. 您可以将此属性设置为您选择的任意对象。 In this case, you would set it to the appropriate fruit object. 在这种情况下,您可以将其设置为适当的水果对象。

Example: 例:

chkBox.Tag = appleObj;

Another Option 另外一个选项

As an option, have you considered binding the TreeView's ItemsSource property to a collection of your fruit objects? 作为一种选择,您是否考虑过将TreeView的ItemsSource属性绑定到您的水果对象的集合? You would set the TreeView's DisplayMemember property (which in inherits from ItemsControl) to the property on your fruit class that contains the name of the particular fruit. 您可以将TreeView的DisplayMemember属性 (从ItemsControl继承)设置为水果类上的属性,该属性包含特定水果的名称。 This would save you the work of hard-coding your check boxes. 这将节省您对复选框进行硬编码的工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM