Вы можете создать один класс TreeViewItemWithCheckbox, расширив класс TreeViewItem, как показано ниже:
public class TreeViewItemWithCheckbox : TreeViewItem
{
#region Variable Declaration
CheckBox chkBox = new CheckBox();
StackPanel stpContent = new StackPanel();
#endregion
#region Properties
public string HeaderText
{
get { return chkBox.Content.ToString(); }
set { chkBox.Content = value; }
}
public bool IsChecked
{
get { return chkBox.IsChecked.Value; }
set { chkBox.IsChecked = value; }
}
#endregion
#region Constructor
public TreeViewItemWithCheckbox()
{
stpContent.Orientation = Orientation.Horizontal;
chkBox = new CheckBox();
chkBox.VerticalAlignment = VerticalAlignment.Center;
chkBox.Click += new RoutedEventHandler(SetCheckboxes);
chkBox.Margin = new Thickness(0, 0, 0, 0);
stpContent.Children.Add(chkBox);
Header = stpContent;
}
#endregion
#region Event Handlers
private void SetCheckboxes(object sender, RoutedEventArgs e)
{
TreeViewItemWithCheckbox selectedItem = ((TreeViewItemWithCheckbox)((StackPanel)((CheckBox)sender).Parent).Parent);
if (selectedItem != null)
{
/* Set checkboxes for all child items */
if (selectedItem.Items.Count > 0)
{
SetChildItemCheckboxes(selectedItem, selectedItem.IsChecked);
}
/* Check if all childs checked then check/uncheck parent accoringly */
if (selectedItem.Parent.GetType() == typeof(TreeViewItemWithCheckbox))
{
TreeViewItemWithCheckbox parentItem = (TreeViewItemWithCheckbox)selectedItem.Parent;
bool bIsAllChecked = true;
foreach (TreeViewItemWithCheckbox item in parentItem.Items)
{
if (!item.IsChecked)
{
bIsAllChecked = false;
break;
}
}
parentItem.IsChecked = bIsAllChecked;
}
}
}
private void SetChildItemCheckboxes(TreeViewItemWithCheckbox item, bool IsChecked)
{
if (item.Items.Count > 0)
{
foreach (TreeViewItemWithCheckbox childItem in item.Items)
{
SetChildItemCheckboxes(childItem, IsChecked);
item.IsChecked = IsChecked;
}
}
else
item.IsChecked = IsChecked;
}
#endregion
}
Затем вам нужно добавить древовидные узлы из 2 списков, как показано ниже:
trvTest.Items.Clear();
//Add default root element
TreeViewItemWithCheckbox rootNode = new TreeViewItemWithCheckbox();
rootNode.HeaderText = "Root";
rootNode.IsExpanded = true;
trvTest.Items.Add(rootNode);
if (_project.list1.Count > 0)
{
TreeViewItemWithCheckbox nodeHead1 = new TreeViewItemWithCheckbox();
nodeHead1.HeaderText = "Listing 1";
rootNode.Items.Add(nodeHead1);
TreeViewItemWithCheckbox node1;
for (int i = 0; i < _project.list1.Count; i++)
{
node1 = new TreeViewItemWithCheckbox();
node1.HeaderText = _project.list1[i].Name;
nodeHead1.Items.Add(node1);
}
}
if (_project.list2.Count > 0)
{
TreeViewItemWithCheckbox nodeHead2 = new TreeViewItemWithCheckbox();
nodeHead2.HeaderText = "Listing 2";
rootNode.Items.Add(nodeHead2);
TreeViewItemWithCheckbox node2 = new TreeViewItemWithCheckbox();
for (int i = 0; i < _project.list2.Count; i++)
{
node2 = new TreeViewItemWithCheckbox();
node2.HeaderText = _project.list2[i].Name;
nodeHead2.Items.Add(node2);
}
}