2010-11-20 191 views
0

我很確定我正在做一些可怕的錯誤,但無法弄清楚。WPF綁定不工作

我圍繞一個類創建了一個簡單的包裝,並添加了一個依賴項屬性,所以我可以綁定到它。但是,綁定不會導致錯誤,但什麼也不做。

爲了簡化事情,我將類更改爲TextBox,並得到了相同的結果。

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 
} 

當我運行下面的XAML第一個給出的結果,但第二個(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,你打我:) – 2010-11-20 10:49:52

+0

簡直太神奇了。我從來沒有在任何地方看到過這種文件,但它效果很好謝謝。 – Telavian 2010-11-20 10:59:47