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]
[/xml]
So what we have here is a ControlTemplate combined with a Style. The ControlTemplate overrides the usual content of the label and we have a style to hook up the template, stretch our content template to fit the size of the label, and make things look generally pretty.
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.
Gotta say, this is one nifty trick. I’m most def. going to play with it!
Best of luck!
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
@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 …}”.