Reputation: 1808
In my program I have a UserControl that contains a TreeView
. That TreeView
has a ViewModel and a Model relating to it. I would like to make it so that by clicking buttons, I can shift nodes up and down throughout the tree. This is similar to what one might implement on a listBox
.
As a guide, I am using this article.
I am implementing the following functions into the code-behind of the UserControl for which the TreeView
exists.
//Move up
private void moveUp_Click(object sender, RoutedEventArgs e)
{
if(UCViewModel.TreeView.SelectedItem != null)
{
if(UCViewModel.TreeView.SelectedItem is TreeModel)
{
TreeModel tm = UCViewModel.TreeView.SelectedItem as TreeModel;
if(tm.Rank != 1)
{
}
}
}
}
private void MoveUp(TreeModel tm)
{ //My guess on how to call the equivalent command...
foreach (TreeModel item in // **UCViewModel.TreeView.GetAllChildren....? )
{
}
}
Because my structure is different, and I am actually implementing an ObservableCollection
as a TreeView
, I do not have access to the same methods as the code in the example.
The following lines are the lines that I am concerned about...
TreeView.Items();
TreeView.Items.Clear();
TreeView.Items.Add();
How can I make the equivalent calls with the way my TreeView
is setup? Please let me know if more code would be helpful.
Upvotes: 0
Views: 498
Reputation: 8791
The main idea of MVVM is not to use anything like treeView.Items.Add() or treeView.GetAllChildren() or whatever method you need from TreeView.
MVVM Pattern says you dont care about View and you dont know about the View or any control inside the View.
Therefore if you have an ObservableCollection as ItemsSource in your ViewModel you just need to move items there and the TreeView will follow you.
As simple as that. Your TreeView just needs to know where the ObservableCollection is placed inside your ViewModel.
Whenever you change something inside ObservableCollection you trigger collection changed event with appropriate event arguments holding information whether you added new items or shifted items around. That is how TreeView will know what to do.
Upvotes: 1