Wpf 将命令目标设置为模板零件
1) 带有命令绑定的自定义数据网格 2) RoutedCommand定义 3) 命令目标定义。(XAML) 政务司司长:Wpf 将命令目标设置为模板零件,wpf,routed-commands,Wpf,Routed Commands,1) 带有命令绑定的自定义数据网格 2) RoutedCommand定义 3) 命令目标定义。(XAML) 政务司司长: //(1) public class CustomDataGrid : DataGrid { this.CommandBindings.Add(new CommandBinding(Commands.ClearInputCommand, ClearFilter, ClearFilterCan
//(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}"/>
我希望将CommandBindings传输到CustomDataGrid(它的模板中的一个元素)的子级,从而消除对这个“自定义”DataGrid的需求,而只需要对常规DataGrid的模板进行更改
XAML:CustomDataGridTemplate
<Template TargetType="{x:Type p:CustomDataGrid}" >
......
<p:SomeCustomElement x:Name="I WANT TO BE THE COMMAND TARGET !" />
......
</Template>
......
......
我怎样才能做到这一点?是否存在向该命令注册某个CustomElement的错误 好的,在所有RoutedCommands类型的旁边,我放置了一些扩展方法,用它自己的类型注册RoutedCommands
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);
}
}
公共静态类命令
{
公共静态路由命令ClearInputCommand=新路由命令(“ClearInputCommand”,类型(命令));
公共静态无效注册表命令(此UIElement UIElement,RoutedCommand命令,ExecutedRoutedEventHandler执行,CanExecuteRouteEventHandler canExecute=null)
{
RegisterCommand(新的CommandBinding(command、execute、canExecute));
}
公共静态无效注册表命令(此UIElement UIElement,CommandBinding CommandBinding)
{
RegisterClassCommandBinding(typeof(object),commandBinding);
}
公共静态void unregister命令(此UIElement UIElement,RoutedCommand命令)
{
对于(int i=0;i
然后从该类的构造函数中调用它,我不确定是否需要取消注册,这对我来说可能会导致内存泄漏,因为它包含对Execute和CanExecute委托的引用
为了注销它们,我必须跟踪所有已注册的uielements,并在应用程序关闭时清除CommandBindings
我认为更好的解决方案是使用类似棱镜复合命令的东西。但现在就可以了