You should use the StringFormat
on the Binding
. You can use either standard string formats, or custom string formats:
<TextBox Text="{Binding Value, StringFormat=N2}" />
<TextBox Text="{Binding Value, StringFormat={}{0:#,#.00}}" />
Note that the StringFormat
only works when the target property is of type string. If you are trying to set something like a Content
property (typeof(object)
), you will need to use a custom StringFormatConverter
(like here), and pass your format string as the ConverterParameter
.
Edit for updated question
So, if your ViewModel
defines the precision, I'd recommend doing this as a MultiBinding
, and creating your own IMultiValueConverter
. This is pretty annoying in practice, to go from a simple binding to one that needs to be expanded out to a MultiBinding
, but if the precision isn't known at compile time, this is pretty much all you can do. Your IMultiValueConverter
would need to take the value, and the precision, and output the formatted string. You'd be able to do this using String.Format
.
However, for things like a ContentControl
, you can much more easily do this with a Style
:
<Style TargetType="{x:Type ContentControl}">
<Setter Property="ContentStringFormat"
Value="{Binding Resolution, StringFormat=N{0}}" />
</Style>
Any control that exposes a ContentStringFormat
can be used like this. Unfortunately, TextBox
doesn't have anything like that.