WPF验证不会触发TextBox的第一个LostFocus [英] WPF Validation Not Firing on First LostFocus of the TextBox
本文介绍了WPF验证不会触发TextBox的第一个LostFocus的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下是Customer.cs类:
public class Customer :IDataErrorInfo
{
public string FirstName {get;组; }
public string LastName {get;组; }
public string Error
{
get {throw new NotImplementedException(); }
public string this [string columnName]
{
get
{
string result = null;
$ b $ if(columnName.Equals(FirstName))
{
if(String.IsNullOrEmpty(FirstName))
{
result =FirstName不能为空或空。
if(columnName.Equals(LastName))
{
if(String.IsNullOrEmpty(LastName))
{
结果=姓氏不能为空或空白;
}
}
返回结果;
这里是WPF代码:
< TextBlock Grid.Row =1Margin =10Grid.Column =0> LastName< ; / TextBlock的>
< TextBox Style ={StaticResource textBoxStyle}Name =txtLastNameMargin =10
VerticalAlignment =TopGrid.Row =1Grid.Column =1>
< Binding Source ={StaticResource CustomerKey}Path =LastName
ValidatesOnExceptions =TrueValidatesOnDataErrors =True
UpdateSourceTrigger =LostFocus/>
< / TextBox>
解决方案在你的代码背后的逻辑,你可以像这样处理实际的 LostFocus 事件:
$ b .xaml
< TextBox LostFocus =TextBox_LostFocus....
.xaml.cs ((Control)sender).GetBindingExpression(TextBox.TextProperty).UpdateSource(); p $ p $ {code> private void TextBox_LostFocus(object sender,RoutedEventArgs e)
}
I am trying to validate the WPF form against an object. The validation fires when I type something in the textbox lose focus come back to the textbox and then erase whatever I have written. But if I just load the WPF application and tab off the textbox without writing and erasing anything from the textbox, then it is not fired.
Here is the Customer.cs class:
public class Customer : IDataErrorInfo
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Error
{
get { throw new NotImplementedException(); }
}
public string this[string columnName]
{
get
{
string result = null;
if (columnName.Equals("FirstName"))
{
if (String.IsNullOrEmpty(FirstName))
{
result = "FirstName cannot be null or empty";
}
}
else if (columnName.Equals("LastName"))
{
if (String.IsNullOrEmpty(LastName))
{
result = "LastName cannot be null or empty";
}
}
return result;
}
}
}
And here is the WPF code:
<TextBlock Grid.Row="1" Margin="10" Grid.Column="0">LastName</TextBlock>
<TextBox Style="{StaticResource textBoxStyle}" Name="txtLastName" Margin="10"
VerticalAlignment="Top" Grid.Row="1" Grid.Column="1">
<Binding Source="{StaticResource CustomerKey}" Path="LastName"
ValidatesOnExceptions="True" ValidatesOnDataErrors="True"
UpdateSourceTrigger="LostFocus"/>
</TextBox>
解决方案
If you're not adverse to putting a bit of logic in your code behind, you can handle the actual LostFocus event with something like this:
.xaml
<TextBox LostFocus="TextBox_LostFocus" ....
.xaml.cs
private void TextBox_LostFocus(object sender, RoutedEventArgs e)
{
((Control)sender).GetBindingExpression(TextBox.TextProperty).UpdateSource();
}
这篇关于WPF验证不会触发TextBox的第一个LostFocus的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文