.FormatString property having no effect on binding

Viewed 444

I have this line in my code

UserLoginLabel.DataBindings.Add(new Binding("Text", Foo, "bar.Username"));

Which display the username (and just the username) in the textbox correctly. How come this code

Binding b = new Binding("Text", Foo, "bar.Username")
{
    FormatString = "Logged in as {0}.",
    FormattingEnabled = true
};
UserLoginLabel.DataBindings.Add(b);

has the exact same effect? Is this not how to format a data binding?

1 Answers

You need to use the Format event for this:

var b = new Binding("Text", Foo, "bar.Username");
b.FormattingEnabled = true;
b.Format += b_Format;
UserLoginLabel.DataBindings.Add(b);

private void b_Format(Object sender, ConvertEventArgs e)
{
    if (e.DesiredType == typeof(String))  //optional, you decide
        e.Value = $"Logged in as {e.Value}.";
}

What you have to watch out for is that this will be called every time the value is to be formatted. That can happen for multiple reasons, so you could get an already-formatted e.Value.

Related