我正在尝试将父项Window
传递给命令,以便可以将其用于RoutedCommand
。有什么办法可以用Dependency Properties
做到这一点?我已经看到很多问题,说这是不可能的,因为它不是可视化树的一部分,但是下面的方法可行:
<Button CommandParameter="{Binding ElementName=Main}" .../>
参数实际上设置为Main
(父窗口)。因此,如何使用Dependency Property
在自定义对象上执行此操作?
我尝试在自己的对象DP上设置它时收到的错误:
System.Windows.Data错误:2:找不到目标元素的管理FrameworkElement或FrameworkContentElement。 BindingExpression :(无路径); DataItem = null;目标元素是“ CommandGroup”(HashCode = 25702951);目标属性是“ CommandParameter”(类型“ Object”)
我的课程如下:
public class CommandGroup : DependencyObject, ICommand
{
public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.Register("CommandParameter", typeof (object), typeof (CommandGroup));
public object CommandParameter
{
get { return (object)GetValue(CommandParameterProperty); }
set { SetValue(CommandParameterProperty, value); }
}
....
}
我想按如下所示设置XAML:
<Button>
<Button.Command>
<CommandGroup CommandParameter={Binding ElementName=Main}>
...
因为CommandParameter不是视觉或逻辑树元素,所以它不能继承DataContext。
...但是当您的对象为Freezable
时,它可以继承DataContext。
public class CommandGroup : Freezable, ICommand
{
public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.Register("CommandParameter", typeof (object), typeof (CommandGroup));
public object CommandParameter
{
get { return (object)GetValue(CommandParameterProperty); }
set { SetValue(CommandParameterProperty, value); }
}
protected override Freezable CreateInstanceCore()
{
return new CommandGroup();
}
}
请参阅:https://thomaslevesque.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/