2010-11-20 34 views
0

私は間違ったことを恐ろしくやっているとは確信していますが、それを理解することはできません。WPFバインディングが動作しない

クラスの周りに単純なラッパーを作成し、それにバインドできるように依存プロパティを追加しました。ただし、バインディングでエラーは発生しませんが、何もしません。

簡単にするために、クラスをTextBoxに変更して同じ結果を得ました。私は次のXAMLを実行すると

public class TextEditor : TextBox 
{ 
    #region Public Properties 

    #region EditorText 
    /// <summary> 
    /// Gets or sets the text of the editor 
    /// </summary> 
    public string EditorText 
    { 
     get 
     { 
     return (string)GetValue(EditorTextProperty); 
     } 

     set 
     { 
     //if (ValidateEditorText(value) == false) return; 
     if (EditorText != value) 
     { 
      SetValue(EditorTextProperty, value); 
      base.Text = value; 

      //if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("EditorText")); 
     } 
     } 
    } 

    public static readonly DependencyProperty EditorTextProperty = 
     DependencyProperty.Register("EditorText", typeof(string), typeof(TextEditor)); 
    #endregion 

    #endregion 

    #region Constructors 

    public TextEditor() 
    { 
     //Attach to the text changed event 
     //TextChanged += new EventHandler(TextEditor_TextChanged); 
    } 

    #endregion 

    #region Event Handlers 

    private void TextEditor_TextChanged(object sender, EventArgs e) 
    { 
     EditorText = base.Text; 
    } 

    #endregion 
} 

最初は結果が得られますが、2番目の1(EditorTextは)さえEditorTextプロパティにヒットしません。

<local:TextEditor IsReadOnly="True" Text="{Binding Path=RuleValue, Mode=TwoWay}" WordWrap="True" /> 
<local:TextEditor IsReadOnly="True" EditorText="{Binding Path=RuleValue, Mode=TwoWay}" WordWrap="True" /> 

答えて

4

あなたはCLRプロパティで余分な作業をしています。 CLRプロパティがWPFで使用されるという保証はありませんので、これを行うべきではありません。その代わりに、DP上のメタデータを使用して同じ効果を達成してください。

public string EditorText 
{ 
    get { return (string)GetValue(EditorTextProperty); } 
    set { SetValue(EditorTextProperty, value); } 
} 

public static readonly DependencyProperty EditorTextProperty = 
    DependencyProperty.Register(
     "EditorText", 
     typeof(string), 
     typeof(TextEditor), 
     new FrameworkPropertyMetadata(OnEditorTextChanged)); 

private static void OnEditorTextChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) 
{ 
    var textEditor = dependencyObject as TextEditor; 

    // do your extraneous work here 
} 
+0

+1、あなたは私にそれを打つ:) –

+0

単純に素晴らしい。私はそれがどこに書かれているか見たことはありませんが、それは素晴らしい作品です。ありがとう。 – Telavian

関連する問題