2012-07-01 51 views
0

我正在開發一個WPF項目。我剛剛創建了一個依賴項屬性。此依賴項屬性旨在使RichTextBox.Selection.Text屬性可綁定如何使用相同的依賴屬性設置和獲取數據?

但我不能做的是使用相同的DP獲取並設置數據到RichTextBox.Selection.Text

這是我使用的,如果我ONLY想用結合從我RichTextBox.Selection.Text數據代碼:

public class MyRichTextBox: RichTextBox 
{ 

    public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
      "Text", 
      typeof(string), 
      typeof(MyRichTextBox), 
      new PropertyMetadata(
       TextPropertyCallback)); 

    public string Text 
    { 
     get { return (string)GetValue(TextProperty); } 
     set { SetValue(TextProperty, value); } 
    } 

    public MyRichTextBox() 
    {   
     this.TextChanged += new TextChangedEventHandler(MyRichTextBox_TextChanged); 
    } 

    void MyRichTextBox_TextChanged(object sender, TextChangedEventArgs e) 
    { 
     Text = this.Selection.Text; 
    } 

和它的作品完美,但與此代碼我無法從我的ViewModel發送任何數據類。

所以,如果我ONLY希望將數據設置爲從我的ViewModel的RichTextBox.Selection.Text屬性我用這個代碼:

public class MyRichTextBox: RichTextBox 
{ 
    public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
     "Text", 
     typeof(string), 
     typeof(MyRichTextBox), 
     new PropertyMetadata(
      TextPropertyCallback)); 

    public string Text 
    { 
     get { return (string)GetValue(TextProperty); } 
     set { SetValue(TextProperty, value); } 
    } 

    private static void TextPropertyCallback(DependencyObject controlInstance, DependencyPropertyChangedEventArgs args) 
    { 
     MyRichTextBox instance = (MyRichTextBox)controlInstance; 
     instance.Selection.Text = (String)args.NewValue; 
    } 

所以,我該怎麼如果我想能夠得到做,使用相同的依賴屬性設置數據?

希望有人能幫助我,tahnk你提前

回答

1

而是結合您的輸入控件的文本到虛擬機的屬性,你已經綁定的附加屬性給它,並在附加屬性的值改變了你設定的輸入控件的文本。

換句話說 - 沒有什麼東西監視到輸入控件文本的改變。

編輯:

你還在做:

instance.Selection.Text = (String)args.NewValue; 

但是,沒有變化的通知instance.Selection.Text

+0

感謝您的回覆,但我已經使用了非附屬屬性,而不是創建了一個繼承了RichTextBox的類,但我仍然遇到同樣的問題。我已經編輯我的問題,我的另一個嘗試 – Dante

+0

是的,我使用事件'TextChanged',但如果我使用此事件和回調,創建一個無限循環 – Dante

+0

與當前值打破循環比較。 –