-1

How could I make wpf UI control like TextBlock display double value in numberic format, for example:

-If double value is 12345, make it display 12.3K or 12,3K.

-If double value is 123, make it display 0,12K or 0.12K.

I had tried StringFormat={}{0:#,}K}, this didnot support 2 digitals behind decimal point.

WPF TextBlock double value format.

Binding="{Binding Volume, StringFormat={}{0:#,}K}"

expect:

-12.3K for 12345;

-0.12K for 123;

ps:I had tried IValueConverter solution.My data is displayed in a datagrid control.By using IValueConverter. I will got "12.3K" not correct data "12345" after copy that to a clipboard.

I think I need a string format way.

Bob
  • 107
  • 6
  • Hi LittleBit, I already look many anwsers, but how to make it works on WPF UI control? eg, TextBlock. – Bob Jan 29 '19 at 08:12
  • Then you should learn how `Binding`s in WPF work. There are tons of Tutorials in the web (eg. like this https://www.wpf-tutorial.com/data-binding/introduction/) – LittleBit Jan 29 '19 at 08:17
  • Put the code from the answer to the duplicate question into a Binding Converter. – Clemens Jan 29 '19 at 09:44
  • Hi Clemens, I know the IValueConverter solution.My data is displayed in a datagrid control. By using IValueConverter, I will got string "1.23K" not correct data "12345" after copy it to clipboard. – Bob Jan 30 '19 at 07:22

1 Answers1

0

You can use a converter when using bindings. Create converter class:

    public class DoubleFormatter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        string formatedDouble = "";
        formatedDouble = System.Convert.ToString(System.Convert.ToDouble(value) / 1000).Substring(0,4) + "K";
        return formatedDouble;
    }


    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }

}

Create static ressource:

    <local:DoubleFormatter  x:Key="DoubletoKFormat"/>

and use it like this:

    <TextBlock Text="{Binding Header, Converter={ StaticResource DoubletoKFormat }}"/>
Denis Schaf
  • 2,478
  • 1
  • 8
  • 17
  • Yes, I know this . My data is displayed in a datagrid, if I use IValueConverter I will get string "1.23K" not the raw data "12345" after copy to clipboard. – Bob Jan 30 '19 at 07:19