【发布时间】:2010-03-11 12:15:20
【问题描述】:
如果我的表单中某些文本框的验证返回 true,我正在尝试更改按钮的 IsEnabled 属性。所以如果有错误,IsEnabled属性应该设置为false。
由于某种原因,我无法让它工作。 IDataErrorInfo 实现仅在调用 IsEmailValid 属性后调用,因此 Validation.GetHasError 始终返回 false,并且我的按钮永远不会被禁用。
有人可以帮忙吗?
代码:
使用 IDataErrorInfo 验证的文本框
<TextBox Style="{StaticResource textBoxInError}" Name="txtEmail" Grid.Column="1" Grid.Row="2" Width="150" Height="23" HorizontalAlignment="Right" VerticalAlignment="Center">
<TextBox.Text>
<Binding Path="Email" Mode="TwoWay"
ValidatesOnDataErrors="True"
UpdateSourceTrigger="LostFocus"
></Binding>
</TextBox.Text>
</TextBox>
IDataErrorInfo 实现:
public string Error
{
get
{
return null;
}
}
public string this[string name]
{
get
{
string result = null;
#region Email
if (name == "Email")
{
if (!presenter.LenientValidateEmail(Email))
{
result = "Your email address is not valid";
}
}
#endregion
#region Website
#endregion
return result;
}
}
IsEnabled 上的按钮绑定
<Button Name="btnUpdate" IsEnabled="{Binding IsValid}" HorizontalAlignment="Left" Grid.Column="3" Grid.RowSpan="2" Grid.Row="6" Height="23" Width="75" Click="btnUpdate_Click">Update
</Button>
public bool IsValid
{
get
{
return IsEmailValid();
}
}
public string Email
{
get
{
return _email;
}
set
{
_email = value;
OnPropertyChanged("Email"); // executes before IDataErrorInfo Implementation
}
}
private bool IsEmailValid()
{
object el = FindName("txtEmail");
if (el != null)
{
_isEmailValid = Validation.GetHasError((DependencyObject)el); // always false??
if (_isEmailValid)
{
return false;
}
else
return true;
}
return true;
}
//PropertyChanged event handler:
void ProfileView_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
IsEmailValid();
}
【问题讨论】:
标签: c# wpf validation binding