参数不正确。该值不能转换为Single类型。
您将百分比设置为null
的问题,但是float类型永远不能设置为null值。对于这种情况,我们需要在绑定值双向模型时使用IValueConverter
。
public class FloatToString : IValueConverter
{
public object Convert(object value,Type targetType,object parameter,string language)
{
if ((float)value == 0f)
{
return string.Empty;
}
else
{
return value.ToString();
}
}
public object ConvertBack(object value,string language)
{
try
{
if ((string)value == string.Empty)
{
return 0f;
}
return float.Parse(value as string);
}
catch (Exception)
{
return 0f;
}
}
}
用法
<Page.Resources>
<local:FloatToString x:Key="FlotToStringConverter" />
</Page.Resources>
<Grid>
<TextBox Height="44" Text="{x:Bind Percentage,Mode=TwoWay,Converter={StaticResource FlotToStringConverter},UpdateSourceTrigger=PropertyChanged}" />
</Grid>
,
在不查看C#类的情况下,您在这里绑定与xaml关联的页面或窗口的文本和文件后面的代码时,我首先要尝试以下操作。如果这不起作用,您可以尝试其他一些方法。
首先,由于无法将string.Empty的值转换为单个精度浮点整数(float),而引发了异常。
根据提供的信息,您可以采取几种方法,我认为您可以简单地使用Textbox.TextChanged事件,如下所示。另外,您还将希望在下面的文本框中添加一个名称,以便您可以通过x:Name属性访问后面代码中在xaml中声明的字段。
....
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:extensions="using:Microsoft.Toolkit.Uwp.UI.Extensions"
....
<TextBox x:Name="yourTextBoxName"
extensions:TextBoxRegex.ValidationMode="Dynamic"
extensions:TextBoxRegex.ValidationType="Custom"
extensions:TextBoxRegex.Regex="[-+]?[0-9]*\.?[0-9]+"
Text="{x:Bind VM.percentage,Mode=TwoWay}"
TextChanged="Textbox_OnTextChanged" />
然后,您要在代码隐藏文件中添加上面声明的以下事件处理程序。
private void TextBox_OnTextChanged(object sender,TextChangedEventArgs e)
{
if (string.IsNullOrEmpty(yourTextBoxName.Text))
yourTextBoxName.Text = 0;
// Additional logic if needed.
}
如果我没记错的话,您已经应该在其中一个c#文件中使用float.Parse方法或也许使用float.TryParse方法。
如果这会干扰您的绑定,那么我可能还需要查看一小段C#代码才能提供帮助。这种方法还应该使您始终看到0。
如果您喜欢空白,则可以在事件处理程序中稍微或更好地更改逻辑,而不是使用TextBox.TextChanged事件,而可以使用TextBox.KeyUp或TextBox.KeyDown事件,例如这样。
private void TextBox_OnKeyDown(object sender,KeyEventArgs e)
{
if (e.Key == Key.Return)
{
if (string.IsNullOrEmpty(yourTextBoxName.Text))
yourTextBoxName.Text = 0;
}
}
或
private void TextBox_OnKeyUp(object sender,KeyEventArgs e)
{
if (e.Key == Key.Return)
{
if (string.IsNullOrEmpty(yourTextBoxName.Text))
yourTextBoxName.Text = 0;
}
}
本文链接:https://www.f2er.com/3111355.html