148

I feel stupid but cannot find out how to add a text to a WPF Label control in code. Like following for a TextBlock:

DesrTextBlock.Text = "some text";

What is equivalent property in Label for doing it?

DesrLabel.??? = "some text"; //something like this

7 Answers 7

226

Try DesrLabel.Content. Its the WPF way.

6
  • 8
    its just the ContentControl way actually.
    – Scott M.
    Commented Feb 4, 2011 at 20:15
  • 4
    That seems a bit inconsistent, given that the property is called Text for a TextBox but not for a TextBlock... Commented Oct 5, 2013 at 22:40
  • 10
    @BlueRaja-DannyPflughoeft there is no obligation for the content of a Label to be text. It is of type object, so you can make it any WPF or .NET type you like - a button, an image, a green rectangle, even a SqlDataReader if you really want! (though quite what that would represent in a label, I'm not too sure...) Commented Oct 29, 2013 at 10:52
  • when update .Content for a WPF label, it does not always refresh the label. How do we force refresh when control yields to the UI? Commented Oct 22, 2019 at 19:34
  • @DavidJeske are you in another thread? Dispatching might be the trick Commented Oct 22, 2019 at 20:24
34

In normal winForms, value of Label object is changed by,

myLabel.Text= "Your desired string";

But in WPF Label control, you have to use .content property of Label control for example,

myLabel.Content= "Your desired string";
0
6

I believe you want to set the Content property. This has more information on what is available to a label.

4

You can use the Content property on pretty much all visual WPF controls to access the stuff inside them. There's a heirarchy of classes that the controls belong to, and any descendants of ContentControl will work in this way.

0

you can use TextBlock control and assign the text property.

0

do not forgat to add x:name to your MainWindow.xaml

-2

Label myLabel = new Label (); myLabel.Content = "Hello World!";

1
  • 4
    While this code may answer the question, it would be better to include some context, explain how it works, and describe when to use it. Code-only answers are not useful in the long run.
    – ryanyuyu
    Commented Aug 13, 2015 at 19:11

Not the answer you're looking for? Browse other questions tagged or ask your own question.