Define the target command for the template part

1) Custom DataGrid with CommandBindings.

2) Definition of the RoutedCommand.

3) Definition of the target team. (Xaml)

CS:

//(1) public class CustomDataGrid : DataGrid { this.CommandBindings.Add(new CommandBinding(Commands.ClearInputCommand, ClearFilter, ClearFilterCanExecute)); } //(2) public static class Commands { public static RoutedCommand ClearInputCommand = new RoutedCommand("ClearInputCommand", typeof(Commands)); } 

XAML:

  <!-- (3) --> <local:CustomDataGrid x:Name="grid" /> <Button Command="{x:Static p:Commands.ClearInputCommand}" CommandTarget="{Binding ElementName=grid}"/> 

I would like to pass CommandBindings to the child of my CustomDataGrid (an element in its template), thereby dissolving the need for this β€œCustom” DataGrid and only changing the template of a regular DataGrid.

XAML: CustomDataGridTemplate.

  <Template TargetType="{x:Type p:CustomDataGrid}" > ...... <p:SomeCustomElement x:Name="I WANT TO BE THE COMMAND TARGET !" /> ...... </Template> 

How can i achieve this? is there SomeCustomElement registration for this command?

0
source share
1 answer

Okay, so along with all the types of RoutedCommands, I have posted several extension methods to register a routed command with a type that is itself

 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 this class, I'm not sure that I need to unregister this hard one, it seems to me that this can cause a memory leak, since it contains references to the Execute and CanExecute delegates.

to unregister, I would have to keep track of all registered accounts and clear CommandBindings when the application was closed.

I think the best solution would be to use something like CompositeCommand prisms. but now it will be done.

0
source

All Articles