问题是如果我直接单击按钮,Silverlight 不会通知我有关异常的信息。一切都很好,如果我在文本框中写了一些东西并将其删除。
我有一个名为 UserLogin 的类。
public class UserLogin
{
//---------------------------------------------------
// Fields
private string _userName;
private string _password;
//----------------------------------------------------
// Properties
public string Username
{
get
{
return _userName;
}
set
{
if (value.Length==0)
{
throw new Exception("You must enter Username");
}
_userName = value;
}
}
public string Password
{
get
{
return _password;
}
set
{
if (value.Length==0)
{
throw new Exception("You must enter password");
}
_password = value;
}
}
}
在 xaml 中:
<StackPanel BindingValidationError="LoginStackPanel_BindingValidationError">
<TextBox x:Name="UsernameTextBox" Text="{Binding Username, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=True}"/>
<PasswordBox x:Name="PasswordBox" Password="{Binding Password, Mode=TwoWay,ValidatesOnExceptions=True, NotifyOnValidationError=True}"/>
<Button x:Name="LoginButton" Content="Sign In" />
</StackPanel>
这是 BindingValidationError 事件。我只是在更改对象的背景并为它们设置工具提示。
private void LoginStackPanel_BindingValidationError(object sender, ValidationErrorEventArgs e)
{
if (e.Action == ValidationErrorEventAction.Added)
{
if (e.OriginalSource is TextBox)
{
(e.OriginalSource as TextBox).Background = new SolidColorBrush(Colors.Yellow);
ToolTipService.SetToolTip((e.OriginalSource as TextBox), e.Error.Exception.Message);
}
else if (e.OriginalSource is PasswordBox)
{
(e.OriginalSource as PasswordBox).Background = new SolidColorBrush(Colors.Yellow);
ToolTipService.SetToolTip((e.OriginalSource as PasswordBox), e.Error.Exception.Message);
}
}
else if (e.Action == ValidationErrorEventAction.Removed)
{
if (e.OriginalSource is TextBox)
{
(e.OriginalSource as TextBox).Background = new SolidColorBrush(Colors.White);
ToolTipService.SetToolTip((e.OriginalSource as TextBox), null);
}
else if (e.OriginalSource is PasswordBox)
{
(e.OriginalSource as PasswordBox).Background = new SolidColorBrush(Colors.White);
ToolTipService.SetToolTip((e.OriginalSource as PasswordBox), null);
}
}
}