简体   繁体   English

如何绑定到 UIElement

[英]How to bind to UIElement

I am trying to pass the parent Window in to a command so that it can be used for a RoutedCommand .我试图将父Window传递给一个命令,以便它可以用于RoutedCommand Is there any way to do this with Dependency Properties ?有什么办法可以用Dependency Properties做到这一点吗? Ive seen a lot of questions that say this isn't possible because it isn't part of the visual tree, but the below works:我看到很多问题都说这是不可能的,因为它不是可视化树的一部分,但以下有效:

<Button CommandParameter="{Binding ElementName=Main}" .../>

The parameter is actually set as Main (the parent Window).该参数实际上设置为Main (父窗口)。 So, how can I do this on my custom object with a Dependency Property ?那么,如何使用Dependency Property对我的自定义对象执行此操作?

The error I get when I try to set it on my own object DP:当我尝试在我自己的对象 DP 上设置它时出现的错误:

System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. System.Windows.Data 错误:2:找不到目标元素的管理 FrameworkElement 或 FrameworkContentElement。 BindingExpression:(no path); BindingExpression:(无路径); DataItem=null;数据项=空; target element is 'CommandGroup' (HashCode=25702951);目标元素是“CommandGroup”(HashCode=25702951); target property is 'CommandParameter' (type 'Object')目标属性是“CommandParameter”(类型“Object”)

My class is as follows:我的课如下:

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); }
  }

  ....
}

I want to set the XAML as below:我想设置 XAML 如下:

<Button>
  <Button.Command>
    <CommandGroup CommandParameter={Binding ElementName=Main}>
    ...

Because CommandParameter is not a visual or logical tree element, it cannot inherit DataContext.因为 CommandParameter 不是可视化或逻辑树元素,所以它不能继承 DataContext。

...but when your object is Freezable , it can inherit 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();
    }
}

See: https://thomaslevesque.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/请参阅: https : //thomaslevesque.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM