在自定义 RichEditBox 中,我有一个名为 Text 的自定义 DependencyProperty。我的目标只是将该属性双向绑定到位于我的 ViewModel 中的字符串属性。这样我就可以使用 ViewModel 中的字符串来设置/获取自定义 RichEditBox 中的文本。
对于您的方案,您可以为您的自定义 RichEditBox 扩展一个 CustomText 属性。如您所知,您可以通过Document.SetText 和Document.GetText 方法获取或设置RichEditBox 的字符串。然后您可以通过以下方式收听RichEditBox 的文本更改
TextChanged 事件。我创建了一个带有双向绑定 CustomText 属性的CustomRichEditBox。请参考以下代码。
public string CustomText
{
get { return (string)GetValue(CustomTextProperty); }
set
{
SetValue(CustomTextProperty, value);
}
}
public static readonly DependencyProperty CustomTextProperty =
DependencyProperty.Register("CustomText", typeof(string), typeof(CustomRichEditBox), new PropertyMetadata(null, new PropertyChangedCallback(OnCustomTextChanged)));
private static void OnCustomTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
CustomRichEditBox rich = d as CustomRichEditBox;
if (e.NewValue != e.OldValue)
{
rich.Document.SetText(Windows.UI.Text.TextSetOptions.None, e.NewValue.ToString());
}
}
监控RichEditBox文字的变化动态修改View-model。
public CustomRichEditBox()
{
this.DefaultStyleKey = typeof(RichEditBox);
this.TextChanged += CustomRichEditBox_TextChanged;
}
private void CustomRichEditBox_TextChanged(object sender, RoutedEventArgs e)
{
string value = string.Empty;
this.Document.GetText(Windows.UI.Text.TextGetOptions.AdjustCrlf, out value);
if (string.IsNullOrEmpty(value))
{
return;
}
CustomText = value;
}
如果您想将 ViewModel 绑定到代码隐藏文件中的控件,您可以参考以下代码。
Binding myBinding = new Binding();
myBinding.Source = this.DataContext;
myBinding.Path = new PropertyPath("Info");
myBinding.Mode = BindingMode.TwoWay;
myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
BindingOperations.SetBinding(MyEditBox, CustomRichEditBox.CustomTextProperty, myBinding);
我已将code sample 上传到 github。请检查。