デフォルト値を指定すると、依存関係プロパティの実装によってアプリケーションがクラッシュするのはなぜですか?
このコード セグメントは、UserControl オブジェクトのクラス宣言にあります。すべてが正常に動作します - コンパイルして完全に実行します。
public static System.Windows.DependencyProperty DepProp
= System.Windows.DependencyProperty.Register( "Rect",
typeof(System.Windows.Shapes.Rectangle),
typeof(FooControl));
public System.Windows.Shapes.Rectangle Rect
{
get
{ return ((System.Windows.Shapes.Rectangle)(GetValue(DepProp))); }
set
{ SetValue(DepProp, value); }
}
ただし、依存関係プロパティに既定値を追加すると、
コードはコンパイルされますが、UserControl をインスタンス化しようとすると致命的な例外が発生してクラッシュします。
参考までに、私のコードは次のようになりました - PropertyMetaData 行が追加されました:
public static System.Windows.DependencyProperty DepProp
= System.Windows.DependencyProperty.Register( "Rect",
typeof(System.Windows.Shapes.Rectangle),
typeof(FooControl),
new System.Windows.PropertyMetadata(new System.Windows.Shapes.Rectangle()));
public System.Windows.Shapes.Rectangle Rect
{
get
{ return ((System.Windows.Shapes.Rectangle)(GetValue(DepProp))); }
set
{ SetValue(DepProp, value); }
}
Register() の呼び出しから PropertyMetadata を削除すると、プログラムは完全に機能し、クラッシュやその他の問題は発生しません。しかし、後のコードにはデフォルト値が必要です。クラッシュせずにデフォルト値を受け入れるにはどうすればよいですか?
クラッシュすると、次の例外が出力ウィンドウに表示されます。
A first chance exception of type 'System.ArgumentException' occurred in WindowsBase.dll
A first chance exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll
A first chance exception of type 'System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll
私はこれをできるだけ早く機能させる必要があるので、アドバイスは素晴らしいでしょう!