【发布时间】:2014-03-10 21:54:09
【问题描述】:
这个问题是this question 的后续问题。基本上我想做的是以数字顺序将节点添加到我的treeView。现在我正在处理一个子节点列表。每个孩子都有一个DisplayName 的数值。在我的程序中,我有一个循环来检查要添加的节点是否有一个DisplayName 小于循环中当前子节点的DisplayName。如果新孩子的DisplayName 小于正在检查的孩子,我想在已经存在的节点之前添加新节点。我很难找到一种方法来做到这一点。
这是我的代码:
var node = Data.GetAllChildren(x => x.Children).Distinct().ToList().First(x => x.identify == 'B');
//Get # of children -- if children exist
if (node.Children.Count() > 0)
{
newChildTitle = int.Parse(nodeName.Value); //node to add
for (int i = 0; i < node.Children.Count(); i++)
{
currentChildTitle = int.Parse(node.Children.ElementAt(i).DisplayName.Value); //current node value
if (newChildTitle == currentChildTitle) //Check if location already exists
{
MessageBox.Show("Sorry, that location name already exists under this category.", "Duplicate Location Name", MessageBoxButton.OK, MessageBoxImage.Warning);
break;
}
else if (newChildTitle < currentChildTitle) //If new location value is less, add before current location in Tree
{
//CODE WOULD GO HERE**
break;
}
}
}
else //if no children exist, just add
node.Children.Add(CreateBlockingLocation(model, blockTreeCollection, nodeName));
TreeView 的 XAML(TreeView 绑定到 ObservableCollection):
<!-- Tree view items & Functions -->
<TreeView Name="Tree_One" IsEnabled="{Binding DataContext.DataTreeEnabled, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" ItemsSource="{Binding DataTree.Data}" />
TreeView 绑定到的ObservableCollection<HierarchicalVM> 的数据和属性:
private HierarchicalVM _parent;
private ObservableCollection<HierarchicalVM> _children;
public HierarchicalVM()
{
Commands = new ObservableCollection<Command>();
}
//Relationship Properties
public HierarchicalVM Parent
{
get { return _parent; }
set
{
_parent = value;
NotifyPropertyChange(() => Parent);
}
}
public ObservableCollection<HierarchicalVM> Children
{
get { return _children ?? (_children = new ObservableCollection<HierarchicalVM>()); }
set { _children = value; }
}
当前解决方案尝试:
//Gets parent item (Data is the complete Tree)
var node = Data.GetAllChildren(x => x.Children).Distinct().ToList().First(x => x.identify == 'B');
if (!node.Children.Any(n => n.numValue == newNumValue))
{
//Error is on this line: **Operator '.' cannot be applied to operand of type 'void'
node.Children = node.Children.Add(newNode).Orderby(n => n.numValue);
}
【问题讨论】:
-
既然是WPF,为什么你的treeview没有绑定到一个集合,在这种情况下你可以使用集合的InsertAt函数呢?手动弄乱 with children 列表通常不是一个好主意。
-
等等,它绑定到一个集合,也许我只是采取了错误的方法。
-
是的,它应该绑定到一个 ObservableCollection,并且你想修改它,而不是可视元素的子元素。
-
那么
node.Children.Add()不是添加子节点的正确方法吗?那么添加孩子的正确方法是什么? -
您的 XAML 应该以这样一种方式绑定,即您只需更改基础集合并向上传播。您可以发布您的 XAML 和任何相关的 ViewModel 代码吗?
标签: c# wpf treeview nodes children