2017-08-10 3 views
1

これは、私がオンラインで見つけた例に基づいて、依存関係プロパティを持つテキストボックスを拡張することを初めて試みたものです。wpf depedencyプロパティクラッシュを伴うカスタムテキストボックス

私のソリューションは、wpfアプリケーションとクラスライブラリの2つのプロジェクトで構成されています。

ここに私のクラスライブラリです:

namespace CustomTextBox 
{ 
public class CustTextBox : TextBox 
{ 
    public string SecurityId 
    { 
    get { return (string)GetValue(SecurityIdProperty); } 
    set { SetValue(SecurityIdProperty, value); } 
    } 

    // Using a DependencyProperty as the backing store for MyProperty. This enables animation, styling, binding, etc... 
    public static readonly DependencyProperty SecurityIdProperty = 
     DependencyProperty.Register("MyProperty", typeof(string), typeof(CustTextBox), new PropertyMetadata(0)); 
} 
} 

ここで私はCustTextBox(アプリケーション自体がちょうどcaliburn.micro.startを使用して、特別なものではありません)

<Window x:Class="TestWPFApplication.ShellView" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:custom="clr-namespace:CustomTextBox;assembly=CustomTextBox"> 

<Grid> 
    <custom:CustTextBox Text="TESTING"></custom:CustTextBox> 
</Grid> 

</Window> 
を使用しようとするWPFアプリケーションのXAMLです

結果は次のとおりです。 enter image description here

実行すると、この行にクラッシュが発生します。

01実際にあなたがどんな魔法の文字列を避けるために nameof(SecurityId)を使用することができるはずです

public static readonly DependencyProperty SecurityIdProperty = 
    DependencyProperty.Register("SecurityId", typeof(string), typeof(CustTextBox), new PropertyMetadata("0")); 

public static readonly DependencyProperty SecurityIdProperty = 
    DependencyProperty.Register("MyProperty", typeof(string), typeof(CustTextBox), new PropertyMetadata(0)); 

へ:

<custom:CustTextBox Text="TESTING"></custom:CustTextBox> 

答えて

4

あなたが変更する必要があります。

EDIT:また、0PropertyMetadataに渡す方法も気づきました。これは、プロパティを宣言したのと同じ型ではありません。あなたはstringと宣言しましたが、intを渡しています。これをPropertyMetadata("0")として渡すか、プロパティタイプをintに変更してください。

+0

私は変更を加えましたが、私はまだ同じ問題があります。あなたの最後のコメントについて:魔法の文字列は何ですか?あなたは "SecurityId"をnameof(SecurityId)に置き換えることを提案していますか? –

+0

これは私が示唆していることです。なぜなら、 'SecurityId'プロパティの名前を変更しても、依存関係プロパティのSecurityIdを変更するのを忘れてしまった場合、問題があり、その理由を知るのが難しいからです。 –

+0

しかし、Registerの最初の引数としてnameof(SecurityId)を指定しても、問題は解決しません。 –

関連する問題