在我的程序中,我有一个TreeView
,它是通过使用ObservableCollection
通过ViewModel实现的。每个集合都有一个名为Rank
的属性。这应该作为收集物品的索引。更改ViewModel中ObservableCollection的属性而不选择它
在this question,我能得到我的TreeView
节点使用ObservableCollection.Move();
然而,为了交换位置,交换节点的地方后,我需要纠正/更改节点的秩的价值,从而使我可以继续操纵它们。
这应该有助于解释我在做什么:
视图 - 代码隐藏:
//Button Click Event -- This makes the Selected Node switch places with the node above it
private void shiftUp_Click(object sender, RoutedEventArgs e)
{
//if a node is selected
if (UCViewModel.TreeViewViewModel.SelectedItem != null)
{
//If the selected Node is not in the 0 position (can not move up anymore)
if (UCViewModel.TreeViewViewModel.Collection<TreeViewModel>.IndexOf(UCViewModel.TreeViewViewModel.SelectedItem) != 0)
{
int oldIndex = UCViewModel.TreeViewViewModel.SelectedItem.Rank;
int newIndex = oldIndex--;
UCViewModel.TreeViewViewModel.Collection<TreeViewModel>.Move(oldIndex, newIndex);
//**Pseudo code trying to explain what I want to do
//**get item at specific index and change the Rank value
//Collection item at index (newIndex).Rank -= 1;
//Collection item at index (oldIndex).Rank += 1;
}
}
}
用户控件 - XAML:
<TreeView ItemsSource="{Binding TreeViewViewModel.Collection<TreeModel>}" ... />
我怎样才能纠正移动后的值为Rank
?
编辑
如上所述,我在我的TreeView
的数据模型Rank
属性。 @Noctis的答案建议在Rank
值更改后使用该属性对TreeView
进行排序。我在这个主题上最喜欢的问题是here。
我已将SortObservableCollection
类添加到我的程序中,所以现在剩下的就是操纵排名值并进行排序。正确的位置是否来自代码隐藏?基本上上述^部分来自哪里?如果是这样的话,我会有点困惑的确切电话...
代码隐藏:
private void shiftUp_Click(object sender, RoutedEventArgs e)
{
//if a node is selected
if (UCViewModel.TreeViewViewModel.SelectedItem != null)
{
//Moves the selectedNode down one (Up visually, hence shiftUp)
UCViewModel.TreeViewViewModel.SelectedItem.Rank--;
//How would I get the node below the selected one and change the Rank?
//This would be the call to sort. Which needs to be called for the collection
//For some reason, sort does not come up for the collection...
//UCViewModel.TreeViewViewModel.Collection.**Sort(...);
}
}
他们是'TreeView'的模型内声明的公共属性,但如何将改变' Rank'让他们自动重新排序?我问这是因为我创建了“Rank”。它不会自动转换为收集索引。 –
那么,看看[MSDN]中的这篇文章(http://msdn.microsoft.com/en-us/library/system.windows.forms.treeview.sort.aspx)。如果您提供自己的TreeViewNodeSorter,则可以按照您想要的方式对树进行排序。 – Noctis
该文章适用于Windows窗体 –