bilgestackoverflow
bilgestackoverflow

Reputation: 329

how to use wpf contentstringformat for more than one format?

Is there a way to use ContentStringFormat for more than one format like this in tooltip ?

ContentStringFormat="{}{0:N0}{0:P}"

<Slider.ToolTip> <ToolTip Content="{Binding Path=PlacementTarget.Value, RelativeSource={RelativeSource Mode=Self}}" ContentStringFormat="{}{0:N0}" /> </Slider.ToolTip>

This is how it was. When I change ContentStringFormat like this:

ContentStringFormat="{}{0:N0} {0:P}"

it shows 505,000.00 % rather than 50 %

Thanks in advance

Upvotes: 0

Views: 2917

Answers (2)

Clemens
Clemens

Reputation: 128060

When you use the standard numeric format P or p the displayed number is first multiplied by 100 and then formatted like a floating point number with a trailing percent symbol. A precision specifier right after P, e.g. P2 controls the number of decimal digits. See here.

Therefore formatting a value of 0.5 with format P2 results in the string "50.00 %":

What you seem to do is to display the value 50 as number (N0), followed by a percentage (P). The result is the string "50 5,000.00 %" (since the default precision for P is 2).

Upvotes: 1

stijn
stijn

Reputation: 35901

There are three problems here:

  • if it shows 505 instead of 50, the number you input is 5.05 but it should be 0.505
  • Second, if you want 0.505 to be displayed as 50% you'll have to round it first
  • last, you have to use P0

so to round up:

//code
public partial class MainWindow : Window
{
  public MainWindow()
  {
    InitializeComponent();
    DataContext = this;
  }

  private double MyActualNumber
  {
    get { return 0.505; }
  }

  public double Number
  {
    get { return System.Math.Round( 100.0 * MyActualNumber ) / 100.0; }
  }
}

//xaml
<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Label Content="{Binding Path=Number}" ContentStringFormat="{}{0:P0}"/>
</Window>

Upvotes: 2

Related Questions