Skip to content

Instantly share code, notes, and snippets.

@SmashBrando
Created August 13, 2021 15:47
Show Gist options
  • Save SmashBrando/90414d969ffb9a76485ec02764db1872 to your computer and use it in GitHub Desktop.
Save SmashBrando/90414d969ffb9a76485ec02764db1872 to your computer and use it in GitHub Desktop.
public class BindToClickEventCommand : ICommand
{
private Action _handler;
public ViewModelCommand(Control control)
{
// Get the control's Type
Type someTreeViewType = ((UIElement)control).GetType();
// Dig out the undocumented (yes, I know, it's risky) EventHandlerStore
// from the control's Type
PropertyInfo EventHandlersStoreType =
someTreeViewType.GetProperty("EventHandlersStore",
BindingFlags.Instance | BindingFlags.NonPublic);
// Get the actual "value" of the store, not just the reflected PropertyInfo
Object EventHandlersStore = EventHandlersStoreType.GetValue(control, null);
var mi= EventHandlersStore.GetType().GetMethod("GetRoutedEventHandlers", BindingFlags.Public | BindingFlags.Instance);
RoutedEventHandlerInfo[] res = (RoutedEventHandlerInfo[])mi.Invoke(EventHandlersStore, new object[] { CheckedTreeViewItem.CheckedEvent });
var parent = VisualTreeHelper.GetParent(control);
while (!(parent is Window))
{
parent = VisualTreeHelper.GetParent(parent);
}
_handler = () => {
res.First().Handler.Method.Invoke(parent, new object[] { control, new RoutedEventArgs() });
};
}
#region ICommand Members
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
_handler();
}
#endregion
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment