0
votes

I have a little WPF app, that has a TreeView to display hierarchical data. I've created a ViewModel to represent the data to be displayed. Actually there are a couple of concrete ViewModels, because I have different kind of objects on various levels of the hierarchy.

public abstract class TreeViewModelBase
{
    private bool _isSelected;
    public bool IsSelected
    {
        get { return _isSelected; }
        set
        {
            if (value == _isSelected) return;

            _isSelected = value;
            OnItemSelected(this, new TreeViewModelSelectedEventArgs(this));
            RaisePropertyChanged(() => IsSelected);
        }
    }
}

So in order to add a new node to the three I just add a new ViewModel object and let the databinding do it's magic to update the tree. I also wanted to make the recently added node the selected node, so I set the IsSelected property to true.

public class FooTreeViewModel : TreeViewModelBase
{
    public ObservableCollection<BarTreeViewModel> Bars { get; private set; }
    public void AddNewPage(Bar newBar)
    {
        var newBarTreeViewModel = new BarTreeViewModel(newBar);
        Bars.Add(newBarTreeViewModel);
        newBarTreeViewModel.IsSelected = true;
    }
}

But this is where I seem to have some trouble. I observe that IsSelected for my recently added object is being executed, but just a second later IsSelected for the previous item is being executed. This seems weird to me.

Although the tree is updated correctly, the SelectedItem of the tree points still to the previous node, not the recently added node which was marked with the IsSelected.

Any hints on what I might be missing?

1
OK; sometimes all it takes is to talk with someone about the problem. After I wrote this post I figured: the IsSelected property is called twice, first for the IsSelected=true for the recently added node and the IsSelected=false on the previously selected node. Because I always raise the OnSelectedItem event (which causes the ViewModel to figure out which node is currently selected) the last call wins - which is the previous node. So by changing the code to only call OnSelectedItem when _isSelected is true, this fixed my code.nyn3x

1 Answers

0
votes

OK; sometimes all it takes is to talk with someone about the problem. After I wrote this post I figured: the IsSelected property is called twice, first for the IsSelected=true for the recently added node and the IsSelected=false on the previously selected node. Because I always raise the OnSelectedItem event (which causes the ViewModel to figure out which node is currently selected) the last call wins - which is the previous node. So by changing the code to only call OnSelectedItem when _isSelected is true, this fixed my code.