Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

c# - Two-way binding in AvalonEdit doesn't work

I have used AvalonEdit in my project that is based on WPF and MVVM. After reading this post I created the following class:

public class MvvmTextEditor : TextEditor, INotifyPropertyChanged
{
    public static DependencyProperty DocumentTextProperty =
        DependencyProperty.Register("DocumentText", 
                                    typeof(string), typeof(MvvmTextEditor),
        new PropertyMetadata((obj, args) =>
        {
            MvvmTextEditor target = (MvvmTextEditor)obj;
            target.DocumentText = (string)args.NewValue;
        })
    );

    public string DocumentText
    {
        get { return base.Text; }
        set { base.Text = value; }
    }

    protected override void OnTextChanged(EventArgs e)
    {
        RaisePropertyChanged("DocumentText");
        base.OnTextChanged(e);
    }

    public event PropertyChangedEventHandler PropertyChanged;
    public void RaisePropertyChanged(string info)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(info));
        }
    }
}

and used the following XAML to use this control:

<avalonedit:MvvmTextEditor x:Name="xmlMessage">
   <avalonedit:MvvmTextEditor.DocumentText>
      <Binding Path ="MessageXml" Mode="TwoWay" 
               UpdateSourceTrigger="PropertyChanged">
         <Binding.ValidationRules>
            <local:XMLMessageValidationRule />
          </Binding.ValidationRules>
      </Binding>
   </avalonedit:MvvmTextEditor.DocumentText>
</avalonedit:MvvmTextEditor>

but the binding works OneWay and doesn't update my string property nor run validation rule.

How can I fix binding to work as expected TwoWay?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

WPF bindings do not use your DocumentText property; instead they access the underlying value of the dependency property directly.

Your OnTextChanged method doesn't actually change the value of the underlying dependency property. You will need to copy the value from base.Text into the dependency property on every change:

protected override void OnTextChanged(EventArgs e)
{
    SetCurrentValue(DocumentTextProperty, base.Text);
    base.OnTextChanged(e);
}

This issue would be easier to see if you followed the correct pattern for implementing DependencyProperty: The DocumentText property should use the GetValue/SetValue methods, and not access a different backing store.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...