【发布时间】:2014-07-08 18:28:25
【问题描述】:
我创建了一个需要验证的 Person MVVM 模型。我正在使用 IDataErrorInfo 类并验证用户。但是当屏幕加载时,文本框已经是红色/已验证,表明该字段需要填写。我相信这是因为我在 InitializeComponent 中绑定了 PersonViewModel。我尝试将 LostFocus 用于更新触发器,但没有做任何事情。
这是我的 PersonViewModel:
public class PersonViewModel : IDataErrorInfo
{
private string _firstName;
private string _lastName;
public string LastName { get; set; }
public string Error
{
get { throw new NotImplementedException(); }
}
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
public string this[string columnName]
{
get
{
string validationResult = String.Empty;
switch(columnName)
{
case "FirstName":
validationResult = ValidateFirstName();
break;
case "LastName":
validationResult = ValidateLastName();
break;
default:
throw new ApplicationException("Unknown property being validated on the Product");
}
return validationResult;
}
}
private string ValidateLastName()
{
return String.IsNullOrEmpty(LastName) ? "Last Name cannot be empty" : String.Empty;
}
private string ValidateFirstName()
{
return String.IsNullOrEmpty(FirstName) ? "First Name cannot be empty" : String.Empty;
}
}
这里是 XAML:
<StackPanel>
<TextBlock>First Name</TextBlock>
<TextBox Text="{Binding FirstName, ValidatesOnDataErrors=True, UpdateSourceTrigger=LostFocus}" Background="Gray"></TextBox>
<TextBlock>Last Name</TextBlock>
<TextBox Text="{Binding LastName, ValidatesOnDataErrors=True, UpdateSourceTrigger=LostFocus}" Background="Gray"></TextBox>
</StackPanel>
MainWindow.cs:
public MainWindow()
{
InitializeComponent();
_personViewModel = new PersonViewModel();
this.DataContext = _personViewModel;
}
我错过了什么吗?我不希望在屏幕加载时触发验证。我只希望在用户失去文本框的焦点时触发它。
【问题讨论】:
-
你试过把
UpdateSourceTrigger改成LostFocus -
是的,我将其更新为 LostFocus,但没有任何作用。
-
您的“错误”属性 getter 抛出异常——这可能是个问题?
-
@McGarnagle:WPF 不使用错误,我相信它是 WinForms 遗留下来的。
-
@johndoe 为什么您不希望用户最初看到表单上的要求?