2010-11-20 4 views
0

Я уверен, что делаю что-то ужасно неправильно, но не могу понять это.WPF Binding Not Working

Я создал простую оболочку вокруг класса и добавил свойство зависимости, чтобы я мог привязываться к нему. Однако привязка не дает ошибок, но ничего не делает.

Чтобы упростить вещи, я сменил класс на 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, вы избили меня до этого :) –

+0

Просто потрясающе. Я никогда не видел документально нигде, но он отлично работает. Благодарю. – Telavian

Смежные вопросы