2015-06-03 101 views
1

如何從WPF(System.Windows.Controls.Primitives)TextBoxBase獲取.Text。下面是代碼:WPF TextBoxBase(System.Windows.Controls.Primitives)獲取文本

private TextBoxBase mTextBox; 
    this.mTextBox.Text; 

的WPF控件不包含.Text一個定義,我用一個TextRange也嘗試過,但沒有奏效。下面是代碼:

string other = new TextRange(((RichTextBox)sender).Document.ContentStart, ((RichTextBox)sender).Document.ContentEnd).Text; 

我怎樣才能獲得.Text從我的WPF(System.Windows.Controls.Primitives)TextBoxBase?

+0

更多檢查此https://msdn.microsoft.com/en-us/library/ms754041(v=vs.110).aspx – GANI

+0

沒有這是一個RichTextBox我需要一個TextBoxBase的代碼 –

+0

爲什麼會如果您使用的是「RichTextBox」,則需要「TextBoxBase」的代碼? Text屬性只存在於TextBox類中。 'TextBoxBase'是兩個控件的基類,但它不包含這樣的屬性。無論如何,TextBoxBase是一個抽象類,所以你不能實例化它。請說明你想達到的目標。 – Kryptos

回答

3

WPF RichTextBox控件中沒有任何Text屬性。下面是一個方式來獲得所有文本:

string GetString(RichTextBox rtb) 
{ 
    var textRange = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd); 
    return textRange.Text; 
} 
+0

沒有,那是我說它不起作用的那個。 –

0

如果你質疑停留在

我怎樣才能從我的WPF(System.Windows.Controls.Primitives)爲.text TextBoxBase

然後簡短的回答是:你不能因爲沒有這樣的屬性。

現在唯一已知的從TextBoxBase繼承的控件是TextBoxRichTextBoxTextBox有一個Text財產,但RichTextBox不。

如果您正在使用文本框,你可以投你的對象,然後獲得屬性:

var textBox = mTextBox as TextBox; 
if (textBox != null) 
{ 
    var text = textBox.Text; 
} 
0

也許使用像這樣的擴展方法?

public static string GetTextValue(this TextBoxBase source) 
{ 
    // need to cast TextBoxBase to one of its implementations 
    var txtControl = source as TextBox; 
    if (txtControl == null) 
    { 
     var txtControlRich = source as RichTextBox; 
     if (txtControlRich == null) return null; 
     return txtControlRich.Text; 
    } 

    return txtControl.Text; 
} 

我還沒有測試過這個代碼,但希望你能得到一般的想法。