我在基于 WPF 和 MVVM 的项目中使用了 AvalonEdit。阅读这篇文章后,我创建了以下类:
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));
}
}
}
并使用以下 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>
但绑定有效OneWay
,不会更新我的字符串属性,也不会运行验证规则。
如何修复绑定以按预期工作TwoWay
?