【发布时间】:2013-10-25 20:35:56
【问题描述】:
我创建了一个扩展 RichTextBox 的自定义控件,以便我可以为 xaml 属性创建绑定。只要我只是从视图模型中更新属性,这一切都很好,但是当我尝试在 Richtextbox 中编辑时,属性不会更新回来。
我在扩展版的richtextbox中有如下代码。
public static readonly DependencyProperty TextProperty = DependencyProperty.Register ("Text", typeof(string), typeof(BindableRichTextBox), new PropertyMetadata(OnTextPropertyChanged));
private static void OnTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var rtb = d as BindableRichTextBox;
if (rtb == null)
return;
string xaml = null;
if (e.NewValue != null)
{
xaml = e.NewValue as string;
if (xaml == null)
return;
}
rtb.Xaml = xaml ?? string.Empty;
}
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
在视图中我已经设置了这样的绑定
<Controls:BindableRichTextBox Text="{Binding XamlText, Mode=TwoWay}"/>
在视图模型中,我将 XamlText 创建为普通属性,并在更新时调用 NotifyPropertyChanged 事件。
我希望当用户在 lostfocus 上或直接在编辑期间在 RichTextBox 中输入文本时更新绑定的 XamlText,这并不重要。
如何更改代码以实现这一点?
【问题讨论】:
标签: c# silverlight dependency-properties two-way