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?

MartinStettner
  • 28,719
  • 15
  • 79
  • 106
  • 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. – Andrew Stephens Jul 04 '14 at 09:21

1 Answers1

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

Leonidas
  • 2,440
  • 15
  • 22
user1859022
  • 2,585
  • 1
  • 21
  • 33