简体   繁体   English

舍入WPF绑定中的值

[英]Rounding a Value in the WPF Binding

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" />

使用绑定的StringFormat属性,例如:

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

它对我来说看起来更好;)

In addition to the StringFormat in Femaref's answer you need to get rid of the Mode=OneWayToSource settings. 除了Femaref的答案中的StringFormat之外,您还需要摆脱Mode=OneWayToSource设置。 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. 该模式用于将值从控件推送到绑定对象(如ViewModel),而不接收对代码中的值的更新,这与您尝试执行的操作相反。 You want the OneWay mode for these which happens to be the default for both the TextBlock.Text. 你想要OneWay模式,这恰好是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 . ProgressBar.Value默认使用TwoWay,在这种情况下仍可以正常工作,但您也可以将其设置为Mode=OneWay

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM