0
問題是Silverlight沒有通知我有關異常,如果我直接點擊按鈕。一切都好,如果我已經在文本框中寫了一些東西並將其刪除。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);
}
}
}