2016-02-12 81 views
1

a TextBlockButton內部爲content如何獲取TextBlock的文本(TextBlock是Button的內容)

我想Text財產的TextBlock。請善意建議我如何解決這個問題。

下面的代碼只返回ctSystem.Windows.Controls.TextBlock

string ct = (sender as Button).Content.ToString(); 

當然的ButtonContent真是TextBlockSystem.Windows.Controls.TextBlock
我在計算器發現非常類似的事例,但人們只提供了錯誤的答案。

+2

你試過'字符串克拉=((發件人爲按鈕)。內容爲TextBlock的).Conte nt;'? – ericosg

+1

@ericosg,你是第一個提交正確答案的人。我誠摯地感謝所有提供出色,正確答案的人。我很遺憾你只寫評論而不是回答..非常感謝你! –

回答

2

由於ButtonContentTextBlock你應該考慮(sender as Button).ContentTextBlock然後使用Text屬性是這樣的:

string ct = ((sender as Button).Content as TextBlock).Text; 
+1

非常感謝你的優秀,善良。所有3人都給我帶來了正確的答案。祝您有個舒適的日子! –

2

有解決你的問題幾個方面。第一種是隻投Button內容和獲取文本:

var button = (sender as Button); 
if(button == null) 
{ 
    // handle this scenario 
} 

var textBlockContent = button.Content as TextBlock; 
if(textBlockContent == null) 
{ 
    // handle this scenario 
} 

var ct = textBlockContent.Text; 

第二個你可以找到你TextBlockby name或只是參考,如果你有事件處理程序在同一控制:

var textblock = (TextBlock)this.FindName("YourTextBlockName"); 
if(textblock == null) 
{ 
    // handle this scenario 
} 

var ct = textblock.Text; 

而且你可以試着改變你的XAML代碼只是一個文本存儲在您的按鈕:

<Button Content="YourText" Backround="..." Foreground="..." Style="..." /> 
+0

非常感謝您的出色善良。所有3人都給我帶來了正確的答案。祝您有個舒適的日子! –