光标返回以开始原因
本文关键字:开始 返回 光标 | 更新日期: 2023-09-27 18:33:02
我正在制作一个具有价格字段的Windows Phone应用程序。一旦用户开始键入"我想更新一些其他文本框"。我使用的是 mvvm 灯,因此通常在用户离开文本框之前不会更新属性。
这对我不起作用,所以我找到了这个并实现了它,但我有一个奇怪的问题,我不明白为什么。
当我在框 50 中输入时,该属性首先更新为"5",然后更新为"50",这是预期的,但是当我第一次"."时,什么都没有触发,然后当我输入 5 时,该属性似乎被点击了 3 次,一旦完成,它将光标移回文本框的乞求。
所以不是 0.59,我得到 90.5
代码隐藏
private void txtPrice_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
TextBox textBox = sender as TextBox;
textBox.Text = "";
}
private void txtPrice_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = sender as TextBox;
// Update the binding source
BindingExpression bindingExpr = textBox.GetBindingExpression(TextBox.TextProperty);
bindingExpr.UpdateSource();
}
在模型中
/// <summary>
/// The <see cref="Price" /> property's name.
/// </summary>
public const string PricePropertyName = "Price";
private decimal price = 0.00M;
/// <summary>
/// Sets and gets the Price property.
/// Changes to that property's value raise the PropertyChanged event.
/// </summary>
public decimal Price
{
get
{
return price;
}
set
{
if (price == value)
{
return;
}
RaisePropertyChanging(() => Price);
price = value;
RaisePropertyChanged(() => Price);
}
}
XAML
<TextBox x:Name="txtPrice" Margin="157,16,102,0" TextWrapping="Wrap" VerticalAlignment="Top" InputScope="Number" Text="{Binding WeightConversion.Price, Mode=TwoWay, UpdateSourceTrigger=Explicit}" Tap="txtPrice_Tap" TextChanged="txtPrice_TextChanged" />
问题是"."本身不是有效的小数,因此当绑定尝试更新价格时,它会失败。后者当您输入".5"时,它会将其视为有效数字并更新 Price 的值,但是当价格上涨属性更改并转换回文本时,它会转换为 0.5,这会强制"编程"更新文本框并将光标重置到第一个位置。
要解决此问题,我看到的最佳解决方案可能是使用字符串属性来备份价格并"手动"更新十进制值:
private decimal price = 0.00M;
/// <summary>
/// Sets and gets the Price property.
/// Changes to that property's value raise the PropertyChanged event.
/// </summary>
public decimal Price
{
get
{
return price;
}
set
{
if (price == value)
{
return;
}
RaisePropertyChanging(() => Price);
price = value;
RaisePropertyChanged(() => Price);
this.PriceStr = this.Price.ToString();
}
}
private string priceStr=0.00M.ToString();
/// <summary>
/// Sets and gets the Price property.
/// Changes to that property's value raise the PropertyChanged event.
/// </summary>
public string PriceStr
{
get
{
return priceStr;
}
set
{
if (priceStr == value)
{
return;
}
priceStr = value;
isPriceAValidStr=decimal.TryParse(this.PriceStr, out price);
RaisePropertyChanged(() => Price);
RaisePropertyChanged(() => PriceStr);
}
}
private bool isPriceAValidStr = true;
并将文本绑定更改为PriceStr。
还有另一个问题,即使有InputScope="Number"
,仍然有一些方法可以在文本框中输入文本:
- 通过使用具有一个的手机的Harware键盘(在模拟器中,您可以通过按向下翻页键来模拟它,然后您将能够使用键盘输入文本(。要解决此问题,您可以注册key_down事件并对
e.Key
进行一些条件检查,并通过设置e.Handled = true;
拒绝所有不需要的密钥。您也可以使用它来防止用户输入两次.
- 通过从另一个文本框复制一些文本来启用文本(可能还应该删除 TextChanged 中的所有无效字母(