Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set WPF Binding.StringFormat Property on TextBox via Style

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?

like image 719
MartinStettner Avatar asked Jul 04 '14 07:07

MartinStettner


1 Answers

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

like image 111
user1859022 Avatar answered Nov 15 '22 12:11

user1859022