4

I'm attempting to implement a progress bar with a textbox on top that also displays the progress %. However the percentage is fractional. Is it possible to round a value returned in the dataset via the binding or does it have to be done via the code behind?

<ProgressBar Grid.Row="2" Grid.ColumnSpan="2" Height="25" HorizontalAlignment="Stretch"  Margin="5,5,5,2" Name="pbProgressIndex" VerticalAlignment="Top" Width="Auto" Value="{Binding Path=ProgressIndex, Mode=OneWayToSource}" />
<TextBlock Grid.Row="2" Grid.ColumnSpan="2" Height="25" Name="txtProgressIndex" Text="{Binding Path=ProgressIndex, Mode=OneWayToSource}" Width="Auto" Foreground="Black" FontWeight="Bold" FontSize="14" FontFamily="Verdana" Padding="5" Margin="5,5,5,5" TextAlignment="Center" />

3 Answers 3

6

Use the StringFormat Property of the Binding, eg.:

{Binding Path=ProgressIndex, Mode=OneWayToSource, StringFormat=N2}

The N2 formatting can also be specified the following way:

{}{0:N2}}
2
  • I ended up modifying the dataset to round the value when it was coming in and then using: Text="{Binding Path=ProgressIndex, Mode=OneWay, StringFormat={}{0}%}"
    – jasonk
    Sep 7, 2010 at 21:35
  • The string format should be "N2", the format specifier (letter) needs to come first. See .NET docs on standard format strings: learn.microsoft.com/en-us/dotnet/standard/base-types/… Nov 11, 2020 at 15:29
5
StringFormat={}{0:#.00}

it looks better to me;)

1

In addition to the StringFormat in Femaref's answer you need to get rid of the Mode=OneWayToSource settings. That mode is for pushing values from a control to a bound object (like a ViewModel) without receiving updates made to the value from code, which is the opposite of what you're trying to do. You want the OneWay mode for these which happens to be the default for both the TextBlock.Text. ProgressBar.Value used TwoWay by default, which will still work fine in this case, but you can also set it to Mode=OneWay.

1
  • Good call. I caught it before coming back to see the answer (YAY! copy and paste), but +1 for the attention to detail.
    – jasonk
    Sep 7, 2010 at 21:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.