2013-10-17 17 views
1

我創建了一個擴展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中或直接在編輯期間輸入文本時更新,這並不重要。

如何更改代碼以實現此目的?

回答

0

您需要聽取對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); 
} 
相關問題