I have a TreeView control with 2-level hierarchy. If an item of the second level is selected and a user clicks on another item, I need to ask him whether he is sure to move to another item. If his answer is 'no', I need to prevent another TreeViewItem from selection.
I try this way:
<TreeView.Resources>
<Style TargetType="{x:Type TreeViewItem}">
<EventSetter Event="PreviewKeyDown" Handler="TreeViewItem_OnKeyDown" />
</Style>
</TreeView.Resources>
private void TreeViewItem_OnMouseDown(object sender, MouseButtonEventArgs e)
{
var selectedTreeViewItem = sender as TreeViewItem;
if (selectedTreeViewItem != null)
{
var myData = selectedTreeViewItem.Header as MyData;
if (myData != null && selectedNode != null)
{
if (!selectedNode.DoYouAgreeToMoveToAnotherItem())
{
e.Handled = true;
}
else
{
myTreeView.Focus();
myData.IsNodeSelected = true;
}
}
}
}
In a way that works. However, the problem is that I get OnMouseDown event twice: for the first-level item and for the second level item. For example, for this tree: Russia - Moscow - Piter USA - New-York - Boston If I click Boston, I get first event for the USA and then for Boston. So, I can't distinguish the cases:
- when user clicks on USA
- when user click on Boston and I just get the first part of tunneling event
In TreeViewItem_OnMouseDown I need to know the TreeViewItem which user clicked on.
Could you advice me, how I can determine the TreeViewItem which user clicked on in TreeViewItem_OnMouseDown? Again, if I just check a sender. It maybe USA, but actually user clicked on Boston. So I need to realize that it was Boston.