(Note - this is a re-post as my first question got posted under wrong headline: Here Sorry!)
I have a standard WPF treeview and have bound items to view model classe
Both Meleak and ígor's recommendations are great, but when the double click event handler is bound to TreeViewItem
then this event handler is called for all of the item's parent elements (not just the clicked element). If it is not desired, here is another addition:
private static void OnMouseDoubleClick(object sender, RoutedEventArgs e)
{
Control control = sender as Control;
ICommand command = (ICommand)control.GetValue(CommandProperty);
object commandParameter = control.GetValue(CommandParameterProperty);
if (sender is TreeViewItem)
{
if (!((TreeViewItem)sender).IsSelected)
return;
}
if (command.CanExecute(commandParameter))
{
command.Execute(commandParameter);
}
}
The best approach I've reached is just binding the IsSelected
property from the TreeViewItem to the ViewModel in a Two-way mode and implement the logic in the property setter. Then you can define what to do if the value is true or false, because this property will change whenever the user click an item.
class MyVM
{
private bool _isSelected;
public bool IsSelected
{
get { return _isSelected; }
set
{
if (_isSelected == null)
return;
_isSelected = vale;
if (_isSelected)
{
// Your logic goes here.
}
else
{
// Your other logic goes here.
}
}
}
This avoids a lot of code.
Also, this technique allows you to implement the "onclick" behaviour only in the ViewModels that really need it.