これまで同様の質問がありましたが、詳細な例は見つかりませんでした。依存関係プロパティを使用してUserControlのコンストラクタのパラメータを置き換える方法は?
私はWinフォームのプログラムを持って、そのコンストラクタは、パラメータのcnがあります
public AddFailure(ProSimConnect cn)// constructor in winform
{
this.connection = cn;
InitializeComponent();
...
}
を今、私はWPFのユーザーコントロールでそれをシミュレートし、メインウィンドウにそれを配置する必要があります。 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();
...
}
...
}
それは動作しません - それは "ヌル" の例外を報告します。どこが間違っていますか?ありがとう。
これは、ユーザーコントロールのコンストラクタにパラメータを使用する必要がある機能である:私はそれを呼び出す場所がある
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());
}
}
コンストラクタが返される前に依存プロパティを設定することはできません... – mm8
こんにちは@ mm8、私はコンストラクタの後に置く必要があるのですか? – water
ProSimConnectを使用するコードを、UserControlのコンストラクタから依存関係プロパティのコールバックに移動できます。私の答えを見てください。 – mm8