trainings DependencyObject - 自定义命令



我尝试创建从DependencyObject和ICommand继承的命令。我有以下代码:

public class CustomCommand : DependencyObject, ICommand
{
public static readonly DependencyProperty CommandProperty;
public static readonly DependencyProperty AfterCommandProperty;
static CustomCommand()
{
var ownerType = typeof(CustomCommand);
CommandProperty = DependencyProperty.RegisterAttached("Command", typeof(Action), ownerType, new PropertyMetadata(null));
AfterCommandProperty = DependencyProperty.RegisterAttached("AfterCommand", typeof(Action), ownerType, new PropertyMetadata(null));
}
public Action Command
{
get => (Action)GetValue(CommandProperty);
set => SetValue(CommandProperty, value);
}
public Action AfterCommand
{
get => (Action)GetValue(CommandProperty);
set => SetValue(CommandProperty, value);
}
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
// Command & AfterCommand are always null
}
}

<Button Content="Test">
<Button.Command>
<command:CustomCommand  Command="{Binding Copy}" AfterCommand="{Binding AfterCopy}" />
</Button.Command>
</Button>

当我按下测试按钮时,命令和后命令为空。你有想法吗?最好的方法是什么,因为我无法将 ICommand 引用添加到我的视图模型。

谢谢

您的自定义命令实例不在可视化树中,因此绑定是一个问题。它没有办法获得DataContext。尝试在绑定上放置跟踪:

<Button.Command>
<local:CustomCommand
Command="{Binding TestAction, PresentationTraceSources.TraceLevel=High}"
/>
</Button.Command>

"找不到框架导师"是你将在调试输出中看到的错误。"你无法从这里到达那里"是他们所说的"东下"。XAML 中的上下文是父级到父级的问题,但从此处重要的意义上说,此内容没有父级。

但这很容易解决。使用绑定代理。这是我从Stack Overflow的各种问题和答案中多次窃取的城镇自行车实现:

public class BindingProxy : Freezable
{
protected override Freezable CreateInstanceCore()
{
return new BindingProxy();
}
public object Data
{
get { return (object)GetValue(DataProperty); }
set { SetValue(DataProperty, value); }
}
// Using a DependencyProperty as the backing store for Data.  This enables animation, styling, binding, etc...
public static readonly DependencyProperty DataProperty =
DependencyProperty.Register("Data", typeof(object), typeof(BindingProxy), new UIPropertyMetadata(null));
}

将实例定义为某个包含作用域中的资源,该作用域具有所需Action属性所在的DataContext。 没有路径{Binding}只返回DataContext,在下面的情况下,这将是窗口的视图模型。

<Window.Resources>
<local:BindingProxy
x:Key="MainViewModelBindingProxy"
Data="{Binding}"
/>
</Window.Resources>

并像这样使用它。BindingProxyData属性绑定到视图模型,因此请使用Data.WhateverPropertyYouWant路径。我称我的Action财产TestAction

<Button
Content="Custom Command Test"
>
<Button.Command>
<local:CustomCommand
Command="{Binding Data.TestAction, Source={StaticResource MainViewModelBindingProxy}}"
/>
</Button.Command>
</Button>

:注:

您的AfterCommand属性中还有一个错误:它将CommandProperty传递给 GetValue/SetValue,而不是AfterCommandProperty

相关内容

  • 没有找到相关文章

最新更新