2010-11-20 19 views
0

Je suis assez sûr que je fais quelque chose de terriblement mal, mais ne peux pas le comprendre.WPF liaison ne fonctionne pas

J'ai créé un wrapper simple autour d'une classe et ajouté une propriété de dépendance afin que je puisse lier à elle. Cependant, la liaison ne donne aucune erreur, mais ne fait rien. Pour simplifier les choses, j'ai changé la classe en TextBox, et j'ai obtenu les mêmes résultats.

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 
} 

Quand je lance le XAML suivant la première donne des résultats, mais le second (EditorText) ne touche même pas la propriété 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" /> 

Répondre

4

Vous effectuez un travail supplémentaire dans votre propriété CLR. Il n'y a aucune garantie que votre propriété CLR sera utilisée par WPF, donc vous ne devriez pas le faire. Au lieu de cela, utilisez des métadonnées sur votre DP pour obtenir le même effet.

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, vous m'avez battu :) –

+0

Tout simplement incroyable. Je n'ai jamais vu ça documenté nulle part, mais ça marche très bien. Merci. – Telavian