如何使用Silverlight中的依赖项属性更新自定义控件中的源代码?

问题描述:

我创建了一个扩展RichTextBox的自定义控件,以便我可以为xaml属性创建一个绑定。只要我只是从视图模型更新属性,但是当我尝试在richtextbox中编辑属性不会更新时,它都可以正常工作。如何使用Silverlight中的依赖项属性更新自定义控件中的源代码?

我在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事件正常属性的绑定。

我想要绑定的XamlText在用户在RichTextBox中输入文本时在lostfocus中或直接在编辑期间输入文本时更新,这并不重要。

如何更改代码以实现此目的?

您需要听取对BindableRichTextBox属性Xaml的更改并相应地设置Text属性。这里有an answer描述如何可以实现。使用在那描述的方法将在下面的代码中的结果(未经测试):

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); 
}