Set command target to template part

后端 未结 1 1359
礼貌的吻别
礼貌的吻别 2021-01-24 18:01

1) Custom DataGrid with CommandBindings.

2) A RoutedCommand Definition.

3) A Command Target Definition. (XAML)

CS :

    //(1)
    publi         


        
相关标签:
1条回答
  • 2021-01-24 19:04

    Ok , so along side all the type of RoutedCommands i placed a few extension methods to register the routed command with the type it self ,

    public static class Commands
    {
        public static RoutedCommand ClearInputCommand = new RoutedCommand("ClearInputCommand", typeof(Commands));
    
        public static void RegisterCommand(this UIElement uiElement, RoutedCommand command, ExecutedRoutedEventHandler execute, CanExecuteRoutedEventHandler canExecute = null)
        {
            uiElement.RegisterCommand(new CommandBinding(command, execute, canExecute));
        }
    
        public static void RegisterCommand(this UIElement uiElement, CommandBinding commandBinding)
        {
            CommandManager.RegisterClassCommandBinding(typeof(object), commandBinding);         
        }
    
        public static void UnRegisterCommand(this UIElement uiElement, RoutedCommand command)
        {
            for (int i = 0; i < uiElement.CommandBindings.Count; i++)
            {
                CommandBinding c = uiElement.CommandBindings[i];
                if (c.Command == command)
                {
                    uiElement.CommandBindings.RemoveAt(i);
                }
            }           
        }
    
        public static void UnRegisterCommand(this UIElement uiElement, CommandBinding commandBinding)
        {
            uiElement.CommandBindings.Remove(commandBinding);                               
        }
    } 
    

    and then just called it from the constructor of that class , i'm not sure if i need to unregister this tough it seems to me that this can cause memory leaks , since it holds a reference to the Execute and CanExecute delegates.

    in order to Unregister them i would have to keep track of all the registered uielements and clear there CommandBindings on application shut down.

    i think a better solution would be to use something like prisms CompositeCommand. but this would do for now.

    0 讨论(0)
提交回复
热议问题