【问题标题】:How to bind to UIElement如何绑定到 UIElement
【发布时间】:2015-03-10 16:33:09
【问题描述】:

我正在尝试将父 Window 传递给命令,以便它可以用于 RoutedCommand。有没有办法用Dependency Properties 做到这一点?我看到很多问题说这是不可能的,因为它不是可视化树的一部分,但下面的工作:

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

参数实际设置为Main(父Window)。那么,如何使用Dependency Property 对我的自定义对象执行此操作?

当我尝试在我自己的对象 DP 上设置它时遇到的错误:

System.Windows.Data 错误:2:找不到目标元素的管理 FrameworkElement 或 FrameworkContentElement。 BindingExpression:(无路径);数据项=空;目标元素是“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}>
    ...

【问题讨论】:

  • 当你在你的 DP 上使用它时,什么不起作用?假设它在命令参数上工作,它应该刚刚工作。
  • @BradleyDotNET 更新了我的问题
  • 必须将依赖属性添加到您的自定义按钮中。您是否想通过绑定将值传递给 CommandParameter?
  • @user2880486 我添加了我的课程,这表明我确实添加了 DP。据我所知,问题与绑定源有关...
  • 你为什么要这么做?如果设置 Button 的 CommandParameter(如在您的第一个 XAML sn-p 中),该值将传递给您的 CommandGroup 的 ExecuteCanExecute 方法。所以似乎不需要额外的 CommandParameter 属性。

标签: c# .net wpf dependency-properties


【解决方案1】:

因为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/

【讨论】:

    猜你喜欢
    • 2013-03-30
    • 1970-01-01
    • 1970-01-01
    • 2012-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-10
    • 1970-01-01
    相关资源
    最近更新 更多