C# WPF文本框绑定百分比
我必须将文本框绑定到%值。因此,我对绑定设置了StringFormat属性,如下所示:C# WPF文本框绑定百分比,c#,wpf,format,C#,Wpf,Format,我必须将文本框绑定到%值。因此,我对绑定设置了StringFormat属性,如下所示: <TextBox Text="{Binding Path=BewertungsFaktore.Gewinn, StringFormat=P2, UpdateSourceTrigger=PropertyChanged}" Style="{StaticResource TextBoxStyle}" HorizontalAlignment="Left"/> double fraction; doubl
<TextBox Text="{Binding Path=BewertungsFaktore.Gewinn, StringFormat=P2, UpdateSourceTrigger=PropertyChanged}" Style="{StaticResource TextBoxStyle}" HorizontalAlignment="Left"/>
double fraction;
double percentage;
if (double.TryParse(value, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out percentage))
{
fraction = percentage / 100d;
}
这似乎很管用。但是如果我编辑值,就会出现问题。
例如,如果我输入值1,文本框应将其格式化为1%。
但主要问题是它的格式是100.00%。
另一个问题是,如果我使用的是德语Sys,我是否必须输入“,”instaded of a.”?属性仅控制绑定值的输出字符串。“P2”只需将该值乘以100,并使用两个十进制数字和一个尾随“%”对其进行格式化。输入时,将忽略此格式 如果还需要输入百分比值,则必须使用。这样的转换器还可以以区域性不变的方式解析输入字符串,如下所示:
<TextBox Text="{Binding Path=BewertungsFaktore.Gewinn, StringFormat=P2, UpdateSourceTrigger=PropertyChanged}" Style="{StaticResource TextBoxStyle}" HorizontalAlignment="Left"/>
double fraction;
double percentage;
if (double.TryParse(value, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out percentage))
{
fraction = percentage / 100d;
}
如果您只使用字符串格式,如
{0:F2}%
,那么您将不得不忍受数据库值,如4.23,以表示我无法接受的4.23%(直到它们将“百分比”数据类型引入SQL Server)
我创建了以下值转换器,将文本框中的百分比值(如4.2367%)映射到数据库值(如0.042367):
public class PercentageConverter : IValueConverter
{
//E.g. DB 0.042367 --> UI "4.24 %"
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var fraction = decimal.Parse(value.ToString());
return fraction.ToString("P2");
}
//E.g. UI "4.2367 %" --> DB 0.042367
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
//Trim any trailing percentage symbol that the user MAY have included
var valueWithoutPercentage = value.ToString().TrimEnd(' ', '%');
return decimal.Parse(valueWithoutPercentage)/100;
}
}
请注意格式化字符串(在本例中为“P2”)如何仅限制显示的小数位数,而不限制传递给基础绑定源的小数位数。ok找到了一个解决方案StringFormat={}{0:F2}%,您能否将解决方案作为答案发布并接受它?作为将来的参考,这很好,我一直在努力寻找一个合适的解决方案。谢谢