AvalonEdit中的双向绑定不起作用

Nas*_*adi 9 c# data-binding wpf dependency-properties avalonedit

我在我的项目中使用了AvalonEdit,它基于WPF和MVVM.阅读这篇文章后,我创建了以下课程:

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));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

并使用以下XAML来使用此控件:

<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>
Run Code Online (Sandbox Code Playgroud)

但绑定有效OneWay,不会更新我的字符串属性,也不会运行验证规则.

如何修复绑定以按预期工作TwoWay

Dan*_*iel 7

WPF绑定不使用您的DocumentText属性; 相反,他们直接访问依赖属性的基础值.

您的OnTextChanged方法实际上不会更改基础依赖项属性的值.您需要base.Text在每次更改时将值复制到依赖项属性中:

protected override void OnTextChanged(EventArgs e)
{
    SetCurrentValue(DocumentTextProperty, base.Text);
    base.OnTextChanged(e);
}
Run Code Online (Sandbox Code Playgroud)

如果您遵循正确的模式来实现,则更容易看到此问题DependencyProperty:该DocumentText属性应使用GetValue/ SetValuemethods,而不是访问其他后备存储.