【发布时间】:2020-09-15 00:00:51
【问题描述】:
我是 xaml 的新手,在绑定到 int 属性的文本框时遇到了一些问题。
我的属性是这样定义的:
public Int32 MyInt
{
set
{
if(MyInt!= value)
{
_myInt = value;
OnSpecificModification();
}
}
get
{
return _myInt ;
}
}
private Int32 _myInt = 100;
我的 xaml 中有一个 texbox 绑定到 MyInt,如下所示:
<TextBox PreviewTextInput="NumberValidationTextBox" x:Name="txtDocSteps" x:FieldModifier="private" Text="{Binding Path=DocSteps, UpdateSourceTrigger=PropertyChanged}"/>
NumberValidationTextBox 是在文本框中只允许数字并且是:
private void NumberValidationTextBox(object sender, TextCompositionEventArgs e)
{
Regex regex = new Regex("[^0-9]+");
e.Handled = regex.IsMatch(e.Text);
}
当我在文本框中输入一个数字时一切正常,但当我清除它时,我收到一条错误消息“无法转换''值”。我明白为什么:因为 MyInt 不可为空。我不想要一个可为空的 int 因为我需要一个值。 当我移动到另一个字段或单击单击事件为的验证按钮时,我希望我的属性 (100) 中定义的值替换文本框中的空值:
private void ButtonValidate_Click(object sender, RoutedEventArgs e)
{
Plug.MyInt = int.Parse(txtDocSteps.Text);
Plug.Description = txtUserDescription.Text;
DialogResult = true;
}
感谢您通过简单的解释帮助您了解如何操作。
【问题讨论】: