问题
1) Custom DataGrid with CommandBindings.
2) A RoutedCommand Definition.
3) A Command Target Definition. (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 transfer the CommandBindings to a child of my CustomDataGrid (an Element in it's Template) , thus dissolving the need for a this "Custom" DataGrid and only a change in a 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 a was of registering SomeCustomElement to that command ?
回答1:
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.
来源:https://stackoverflow.com/questions/21511674/set-command-target-to-template-part