Set WPF Binding.StringFormat property to TextBox via style

I have a WPF application containing many TextBox es having different types of bindings, all of which have the same StringFormat property (its technical application, text fields should display values ​​with units of "xxx mm" ...)

I want to configure binding in XAML / Designer, but I would like to avoid setting the TextFormat property on each individual Binding. Is there any way to do this with styles?

If I try to set the binding in Setter for the Text property, for example

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

I need to provide Path in the Setters Value property, and I cannot determine the binding in the XAML itself (since this will override the value given in the style).

Is there a way to set / change only the StringFormat property in one binding (i.e. the Binding property for the Text property) using style?

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

+6
source share
1 answer

perhaps you can bind the DataContext of the text field rather than the text property

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

and then use the installer for example

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

to bind TwoWay you will need a converter anyway to get rid of unnecessary mms

+3
source

Source: https://habr.com/ru/post/971747/


All Articles