I would like to have a TextBox that displays a number in currency format (by setting StringFormat=c on the binding). When the TextBox is selected (when IsKeyboardFocused==true), I would like the formatting to go away, until the focus on the TextBox is lost.
I found a way to do this, code pasted below. My problem with this is that the binding is specified inside the Style – this means I have to retype the style for every TextBox I want to do this for. Idealy I would like to put the style somewhere central, and reuse it for every TextBox, with a different binding target for each.
Is there a way for me, using a Style, to set a parameter on the existing binding, something like Text.Binding.StringFormat="" ? (As opposed to setting the entire value of Text to a newly defined Binding)
Other suggestions to accomplish this would also be appreciated.
Code (this works, it’s just inconvenient):
<TextBox x:Name="ContractAmountTextBox">
<TextBox.Style>
<Style TargetType="{x:Type TextBox}">
<Style.Triggers>
<DataTrigger Binding="{Binding IsKeyboardFocused, ElementName=ContractAmountTextBox}" Value="False">
<Setter Property="Text" Value="{Binding Path=ContractAmount, UpdateSourceTrigger=LostFocus, StringFormat=c}"/>
</DataTrigger>
<DataTrigger Binding="{Binding IsKeyboardFocused, ElementName=ContractAmountTextBox}" Value="True">
<Setter Property="Text" Value="{Binding Path=ContractAmount, UpdateSourceTrigger=LostFocus}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBox.Style>
It is feasible with an attached property, but it means you have to replace the binding entirely, then put it back.
Here’s a quick and dirty implementation:
Usage:
Using this, you can also reuse the style for different TextBoxes