A.D.
A.D.

Reputation: 1116

difference when binding a Label and a TextBox (XAML)

Just found out something that I am very surprised with.

XAML code:

  <Label  Content="{Binding myParameter}"/>
  <TextBox Text="{Binding myParameter}" />

myParameter is an instance of a class whose ToString() method is overridden:

public override string ToString()
{
    Console.WriteLine("Displaying value: " + Name);
    return Name;
}

When rendering: the label invokes ToString() and displays the Name property. the TextBox does not display anything

Can I get some explanation why?

Upvotes: 2

Views: 64

Answers (2)

ViVi
ViVi

Reputation: 4464

As per Textbox Documentation in MSDN TextBox.Text Property is of type string :

public string Text { get; set; }

and as per Label documentation in MSDN Label.Content Property is of type object :

public object Content { get; set; }

Hence assigning some value to TextBox.Text will not call the ToString() method that you have overridden, since it is already of type string. Label.Content calls the method since the object is being converted to string.

Upvotes: 2

Silas Reinagel
Silas Reinagel

Reputation: 4203

Content is expected to be any object, which means that ToString() will be called.

Text is expected to be a String property. If Text is not bound to a String property, then the framework error handling kicks in and it displays nothing.

The best practice is to bind directly to the values you wish to display, rather than a parent object. In this case, bind to the Name property, directly.

Upvotes: 2

Related Questions