Diego Torres's answer is clean and simple! But for those who don't want to install a NuGet Package just for this purpose, you can create your own dependency property that Execute Command when a even is fired.
namespace View.Helper
{
public class EventToCommandAdaptor
{
public static readonly DependencyProperty TreeViewSelectedItemChangedCommand_DpProp =
DependencyProperty.RegisterAttached(
"TreeViewSelectedItemChangedCommand",
typeof(ICommand),
typeof(EventToCommandAdaptor), // owner type
new PropertyMetadata(new PropertyChangedCallback(AttachOrRemoveTreeViewSelectedItemChangedEvent))
);
public static ICommand GetTreeViewSelectedItemChangedCommand(DependencyObject obj)
{
return (ICommand)obj.GetValue(TreeViewSelectedItemChangedCommand_DpProp);
}
public static void SetTreeViewSelectedItemChangedCommand(DependencyObject obj, ICommand value)
{
obj.SetValue(TreeViewSelectedItemChangedCommand_DpProp, value);
}
public static void AttachOrRemoveTreeViewSelectedItemChangedEvent(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
TreeView treeview = obj as TreeView;
if (treeview != null)
{
ICommand cmd = (ICommand)args.NewValue;
if (args.OldValue == null && args.NewValue != null)
{
treeview.SelectedItemChanged += ExecuteTreeViewSelectedItemChanged;
}
else if (args.OldValue != null && args.NewValue == null)
{
treeview.SelectedItemChanged -= ExecuteTreeViewSelectedItemChanged;
}
}
}
private static void ExecuteTreeViewSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> args)
{
DependencyObject obj = sender as DependencyObject;
ICommand cmd = (ICommand)obj.GetValue(TreeViewSelectedItemChangedCommand_DpProp);
if (cmd != null)
{
if (cmd.CanExecute(args.NewValue))
{
cmd.Execute(args.NewValue);
}
}
}
}
}
Include xmlns:vh="clr-namespace:View.Helper"
in <Windows></Windows>
And the TreeView looks like:
<TreeView ItemsSource="{Binding MyItemSource}"
vh:EventToCommandAdaptor.TreeViewSelectedItemChangedCommand="{Binding MyCommand}">
</TreeView>
I learnt this trick when I encountered a similar situation: I want to execute a command when DataGrid.MouseDoubleClick Event is fired. But sorry that I forgot to mark down the source.