views:

31

answers:

1

I am new to WPF and am having issues with associating a value with an object. I have a TreeView with CheckBoxes and I am wondering how I can associate an object to each checkbox. 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

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.

Here is a code sample for me adding checkboxes to the 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;
A: 

TreeViewItem inherits from FrameworkElement which provides the Tag property for this very purpose. 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? 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. This would save you the work of hard-coding your check boxes.

Ben Gribaudo