C# 如何处理WPF中的百分比输入和显示?
我一直在寻找处理百分比的好方法。在我们的应用程序中,我们需要用不同的小数位数显示和编辑百分比值,即当用户当前不关注文本框时,它应该显示12.50%,但在编辑值时,它应该显示为0.12501015512311。更糟糕的是,用户应该能够选择在运行时显示的小数位数。此外,应允许用户输入12.5%,这将转换为0.125。我知道我可以用转换器来实现这一点,但我在将所有这些需求结合到一个像样的解决方案中时遇到了麻烦 以下是我迄今为止最好的尝试:C# 如何处理WPF中的百分比输入和显示?,c#,wpf,C#,Wpf,我一直在寻找处理百分比的好方法。在我们的应用程序中,我们需要用不同的小数位数显示和编辑百分比值,即当用户当前不关注文本框时,它应该显示12.50%,但在编辑值时,它应该显示为0.12501015512311。更糟糕的是,用户应该能够选择在运行时显示的小数位数。此外,应允许用户输入12.5%,这将转换为0.125。我知道我可以用转换器来实现这一点,但我在将所有这些需求结合到一个像样的解决方案中时遇到了麻烦 以下是我迄今为止最好的尝试: public class PercentConverter :
public class PercentConverter : IValueConverter
{
private static int numberOfDecimals = CultureInfo.CurrentCulture.NumberFormat.PercentDecimalDigits;
public static int NumberOfDecimals
{
get { return numberOfDecimals; }
set
{
if(value != numberOfDecimals)
{
numberOfDecimals = value;
}
}
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
decimal pct = System.Convert.ToDecimal(value);
CultureInfo ci = new CultureInfo(CultureInfo.CurrentCulture.Name, false);
ci.NumberFormat.PercentDecimalDigits = NumberOfDecimals;
return String.Format(ci, "{0:P}", pct);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
string percentString = value as string;
string doubleString = percentString.TrimEnd(culture.NumberFormat.PercentSymbol.ToCharArray());
double percent = Double.Parse(doubleString, NumberStyles.Any);
if (IsExplicitPercentage(percentString, culture))
{
percent /= 100;
}
return percent;
}
private bool IsExplicitPercentage(string percentString, CultureInfo culture)
{
return percentString.Contains(culture.NumberFormat.PercentSymbol);
}
}
然后在xaml中
<DataGrid.Columns>
<DataGridTextColumn Header="Beskrivelse" Binding="{Binding Description}" />
<DataGridTemplateColumn Header="Share">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox HorizontalContentAlignment="Right" HorizontalAlignment="Stretch">
<TextBox.Style>
<Style TargetType="{x:Type TextBox}">
<!-- Other Style Setters -->
<Setter Property="Text" Value="{Binding Share, Converter={StaticResource pctConverter}}" />
<Style.Triggers>
<Trigger Property="IsKeyboardFocused" Value="True">
<Setter Property="Text" Value="{Binding Share}" />
</Trigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
但这不会正确绑定到datacontex,当我更改textbox中的值时,它不会更新绑定到的模型上的属性
请注意,我对WPF非常陌生,因此可能缺少一些基本内容。您需要修改
文本的绑定属性:
<Setter Property="Text" Value="{Binding Share, Converter={StaticResource pctConverter}, UpdateSourceTrigger=PropertyChanged}" />
这将导致在键入每个字符时,DataContext
对象属性中的值发生更改。默认情况下,属性会在字段失去焦点后更改。事实上,我对LostFocus上的更新很满意,但直到我在绑定中将UpdateSourceTrigger显式设置为LostFocus时,它才起作用。奇怪。。。谢谢;)