Set WPF Binding.StringFormat Property on TextBox via Style
Asked Answered
B

1

8

I have an WPF application contains many TextBoxes having different kind of Bindings which all share the same StringFormat property (its a technical application, the Textboxes should display values with units "xxx mm"...)

I want to set up the Binding in the XAML/Designer, but I'd like to avoid setting the TextFormat property on every individual Binding. Is there a way to do this using Styles?

If I try to set the Binding in a Setter for the Text property like

    <Style x:Name="mmtext" TargetType="TextBox" x:Key="mmtext">
        <Setter Property="Text" Value="{Binding Path=A,StringFormat={}{0} mm}" />
    </Style>

I need to provide a Path in the Setters Value property, and I cannot define any binding in the XAML itself (as this would override the value set in the Style).

Is there a way to set/modify only the StringFormat property in a single Binding (i.e. the Binding for the Text property) using a Style?

Or do I need to look for templating or a custom control?

Briton answered 4/7, 2014 at 7:39 Comment(1)
I'm not aware of a style-based solution. What about a converter? You'll still have to specify the converter in each control's binding of course, so you aren't reducing the amount of XAML you write, but at least the formatting logic is in one place, if you ever need to change it across the entire application.Forsythe
B
7

you could probably bind the DataContext of the textbox rather than the text property

 <TextBox DataContext="{Binding Path=A}" />

and then use a setter like

<Style x:Name="mmtext" TargetType="TextBox" x:Key="mmtext">
    <Setter Property="Text" Value="{Binding Path=., StringFormat={}{0} mm}" />
</Style>

for a TwoWay binding you will need a converter anyways to get rid of the extra mms

Beauvais answered 4/7, 2014 at 11:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.