Saturday, 25 July 2009

De-Selecting all Nodes in Silverlight TreeView

If you are wondering how you can de-select all Nodes in a Silverlight TreeView – here is one way to do it. Attach a a handler to the MouseLeftButtonUp as follows:

<Toolkit:TreeView MouseLeftButtonUp="TreeView_MouseUp"></Toolkit:TreeView>


And use the following event handler code:



private void TreeView_MouseUp(object sender, MouseButtonEventArgs e)
{
if (sender is TreeView && ((TreeView)sender).SelectedItem != null)
{
if(e.OriginalSource is Border)
((TreeViewItem)((TreeView)sender).SelectedItem).IsSelected = false;
}
}


If The expected behaviour is that you can click anywhere on the TreeView surface (of cource not on Any Node) and the currently selected Node will be de-selected.



If you have problems, make sure the Event Handler is actually being called when you press and release the mouse button on the TreeView – you can do this by placing a breakpoint in the event handler.

No comments: