When i bind an object to a WPF control i want to display properties to different levels of precision depending on the unit system being used. For example i have a property IsMetric
if the value is true i want to display the values with one decimal place if it is false then three decimal places. Currently I am adding a static resource string which is added to resources in the constructor before the call to InitialiseComponent()
like this:
public RoomDisplay(Room room)
{
string format = room.IsMetric ? "{0:0.0}" : "{0:0.000}";
this.Resources.Add("format", format);
InitializeComponent();
this.DataContext = room;
}
Then the Xaml looks like this:
<TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Path=Breadth, StringFormat={StaticResource ResourceKey=format}}" TextAlignment="Right" />
This has worked upto now. However this approach falls down with embedded controls, that and i've never been happy with the approach.
I have investigated DataTriggers, something along the lines of:
<DataTrigger Binding="{Binding IsMetric}" Value="true">
<Setter Property="Text" Value="{Binding Breadth, StringFormat=F1}"/>
</DataTrigger>
<DataTrigger Binding="{Binding IsMetric}" Value="false">
<Setter Property="Text" Value="{Binding Breadth, StringFormat=F3}"/>
</DataTrigger>
However this is a pain to add to all the textblocks. Ideally i would like to put this into a style but i cant figure out a way of just setting the StringFormat without the text value.
The other option is to have a format property in the object and bind the StringFormat to that but i would prefer to stay away from this. Any Ideas? Thanks.