views:

502

answers:

2

I have a TreeView control from System.Windows.Controls on MainPage.

<controls:TreeView x:Name="Tree" 
  SelectedItemChanged="Tree_SelectedItemChanged" />

MainPage ctor looks like this:

  public MainPage()
        {
            InitializeComponent();

            for (int i = 0; i < 10; ++i)
               Tree.Items.Add(new TreeViewItem() { Header = i.ToString() } );

            (Tree.Items[0] as TreeViewItem).IsSelected = true;
        }

Just fill TreeView and select first element.

In Tree_SelectedItemChanged I want to do some action with selection item, but Tree.SelectedItem has a null value.

I don't understand why it happens. TreeView in Wpf works fine.

Have you any ideas about it?

+1  A: 

Mmm... That IS stange!
What you could do to bypass this issue is something like this:

private void Tree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
    {
        object SelectedValue;
        if (Tree.SelectedValue == null)
        {
            foreach (object ti in Tree.Items)
            {
                if (((TreeViewItem)ti).IsSelected)
                {
                    SelectedValue = ti;
                    break;
                }
            }
        }
        else
        {
            SelectedValue = Tree.SelectedValue;
        }
    }

Or instead of the Tree.SelectedValue == null, you could also use a bool e.g. isFirstLoad or something like that!
Stange issue this is...

Pieter Nijs
Tnx you for the answer. Probably this behavoir is a silverlight bug.
mt_serg
A: 

It really depends on when you look at the trigger that takes place. If you look at the trigger the first time [i.e. when you set (Tree.Items[0] as TreeViewItem).IsSelected = true; and has a breakpoint at that stage, then you will have selected item as null. The reason being; that trigger takes place in order to set the first selected item.

Just out of interest sake, I changed your code a bit to this.

 for (int i = 0; i < 10; ++i)
            Tree.Items.Add(new TreeViewItem() { Header = i.ToString(), Name = i.ToString()});

        (Tree.Items[0] as TreeViewItem).IsSelected = true;

I placed a breakpoint in the Tree_SelectedItemChanged event, and it triggers as soon as you set (Tree.Items[0] as TreeViewItem).IsSelected = true;. Up until then, the selected item will be null.

If you have the Toolkit installed you can also reference the System.Windows.Controls.Toolkit. You then gain access to a method Tree.SelectItem(Tree.Items[0]). It does not fix the fact that initially it is null, but it also does not trigger the selected item trigger.

However, every time I changed the selection from there onward, the selected item was correct.

Hope this helps.

Johannes