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?

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. Commented Jul 4, 2014 at 9:21

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.