如何在 silverlight 中使用依赖项属性从自定义控件更新源代码
本文关键字:属性 自定义控件 源代码 更新 依赖 silverlight | 更新日期: 2023-09-27 18:35:42
>我创建了一个扩展 RichTextBox 的自定义控件,以便我可以为 xaml 属性创建绑定。只要我只是从视图模型更新属性,一切都很好,但是当我尝试在富文本框中编辑时,属性不会更新回来。
我在富文本框的扩展版本中有以下代码。
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 事件。
我希望当用户在 RichTextBox 中输入文本时,无论是在失去焦点上还是在编辑过程中直接输入文本时,绑定的 XamlText 都会更新,这并不重要。
如何更改代码以实现此目的?
您需要侦听对BindableRichTextBox
的Xaml
-属性的更改,并相应地设置Text
-属性。这里有一个答案,描述了如何实现这一目标。使用中描述的方法将生成以下代码(未经测试):
public BindableRichTextBox()
{
this.RegisterForNotification("Xaml", this, (d,e) => ((BindableRichTextBox)d).Text = e.NewValue);
}
public void RegisterForNotification(string propertyName, FrameworkElement element, PropertyChangedCallback callback)
{
var binding = new Binding(propertyName) { Source = element };
var property = DependencyProperty.RegisterAttached(
"ListenAttached" + propertyName,
typeof(object),
typeof(UserControl),
new PropertyMetadata(callback));
element.SetBinding(property, binding);
}