簡體   English   中英

如何綁定到 UIElement

[英]How to bind to UIElement

我試圖將父Window傳遞給一個命令,以便它可以用於RoutedCommand 有什么辦法可以用Dependency Properties做到這一點嗎? 我看到很多問題都說這是不可能的,因為它不是可視化樹的一部分,但以下有效:

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

該參數實際上設置為Main (父窗口)。 那么,如何使用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}>
    ...

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM