Rounding a value in a WPF binding

I am trying to implement a progress bar with a text box at the top that also displays% progress. However, this percentage is fractional. Is it possible to round the value returned in the dataset through the binding, or should this be done with 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" /> 
+4
source share
3 answers

Use the StringFormat Binding Property, for example:

 {Binding Path=ProgressIndex, Mode=OneWayToSource, StringFormat=2N} 
+6
source
 StringFormat={}{0:#.00} 

it looks better to me;)

+5
source

In addition to StringFormat's answer in Femaref, you need to get rid of the Mode=OneWayToSource . This mode is designed to push values ​​from a control into a related object (for example, ViewModel) without receiving updates made to the value from the code, which is the opposite of what you are trying to do. You need OneWay mode, which is used by default as for TextBlock.Text. ProgressBar.Value by default uses TwoWay, which in this case will work fine, but you can also set it to Mode=OneWay .

+1
source

All Articles