Editable Label in WPF

While still in the dark woods of learning WPF, I was completely lost trying to fulfill a requirement to make an editable label that showed a formatted value when not selected. In my case, the formatted value would round a decimal value to a few digits to make long number more readable.

I asked over on StackOverflow, but didn’t get any responses and ended up posting a link to a real half-baked solution. That solution disallowed me from restyling an individual instance, and forced me to use OnPropertyChanged when binding to it. Yikes!

Now that I’ve fought through a bit more, I have a much better solution and in pure XAML!
[xml]


<ContentPresenter.Content>








</ContentPresenter.Content>

<ControlTemplate.Triggers>










</ControlTemplate.Triggers>


[/xml]

Sample usage:

[xml]

You’ll notice when we’re binding to the content of the Label, we have to use a [generic]RelativeSource TemplatedParent[/generic] binding so we can specify that we’re TwoWay binding on the TextBox and to give the string format on the TextBlock.

All of this is far easier than the alternatives I’ve seen, but it required some deft taming of the WPF.

This entry was posted in Coding and tagged .

3 thoughts on “Editable Label in WPF

  1. Very useful – I’m still new to WPF though, and I@m wondering how I would modify this to force the Enter or Return keys to lose focus. Currently, you either have to hit Tab or click outside the control

    Thanks

  2. @Rob That’s will definitely require an event handler in code-behind. That said, you can always create a global event handler somewhere and bind using “{x:Static …}”.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.