如何使用依赖项属性 来替换UserControl 的构造函数中的参数?

how to use dependency property to replace the parameter in the constructor of a UserControl?

我注意到以前也有人问过类似的问题,但我没有找到任何详细的例子。

我有一个winform程序,它的构造函数有一个参数cn:

    public AddFailure(ProSimConnect cn)// constructor in winform
    {
      this.connection = cn;
      InitializeComponent();
      ...
    }

现在需要在WPF中的UserControl中模拟出来,放到MainWindow中。

在MainWindow.xaml中:

   <Border ...>
   <IOS:Core_System/>
   </Border>

我想这样做,但我知道我做不到,因为它不应该有任何参数:

    public Core_System(ProSimConnect cn)// constructor in UserControl
    {            
        this.cn = connection;
        InitializeComponent();
        ...
    }

因此我尝试使用依赖性 属性:

 public partial class Core_System : UserControl
{
    ProSimConnect connection;

    //dependency property
    public ProSimConnect cn
    {
        get { return (ProSimConnect) GetValue(connectionProperty); }
        set { SetValue(connectionProperty, value); }
    }
    public static readonly DependencyProperty connectionProperty =
        DependencyProperty.Register("cn", typeof(ProSimConnect),typeof(Core_System));

  // constructor in UserControl
  public Core_System()
  {            
      this.connection = cn;
      InitializeComponent();
      ...
  }
      ...
}

它不起作用 - 它报告 "null" 异常。我哪里错了?谢谢。

这是UserControl的构造函数中需要使用参数的函数:

    Failure []getSelectedFailures()
    {
        return cn.getFailures().Where(failure => failure_name.Contains(failure.name)).ToArray();
    }

我调用的位置是:

public partial class Core_System : UserControl
{
  ...
    private void button_Engine_1_On_Fire(object sender, RoutedEventArgs e)
    {
       ...
       ArmedFailure.create(getSelectedFailures());
    }
}

在构造函数返回之前无法设置依赖项属性。

您可以将任何使用 ProSimConnect 的代码从 UserControl 的构造函数移动到依赖项 属性 回调:

public partial class Core_System : UserControl
{
    ProSimConnect connection;

    //dependency property
    public ProSimConnect cn
    {
        get { return (ProSimConnect)GetValue(connectionProperty); }
        set { SetValue(connectionProperty, value); }
    }
    public static readonly DependencyProperty connectionProperty =
        DependencyProperty.Register("cn", typeof(ProSimConnect), typeof(Core_System), new PropertyMetadata(new PropertyChangedCallback(OnPropertySet));

    private static void OnPropertySet(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        Core_System ctrl = d as Core_System;
        ctrl.connection = e.NewValue as ProSimConnect;
        //...
    }

    // constructor in UserControl
    public Core_System()
    {
        InitializeComponent();
    }
}

只要依赖项 属性 被设置为一个值,回调就会被调用。