在WPF中,可以使用ValidationRule类来实现在失去焦点时进行绑定并在属性更改时进行验证的功能。下面是一个示例代码:
创建一个继承自ValidationRule的验证规则类,例如MyValidationRule:
public class MyValidationRule : ValidationRule
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
// 验证逻辑
// 如果验证成功,返回ValidationResult.ValidResult
// 如果验证失败,返回包含错误消息的ValidationResult对象
在XAML中,将该验证规则类应用于绑定的ValidationRules属性:
<TextBox>
<TextBox.Text>
<Binding Path="MyProperty">
<Binding.ValidationRules>
<local:MyValidationRule />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
在ViewModel中,创建一个属性并实现INotifyPropertyChanged接口:
public class ViewModel : INotifyPropertyChanged
private string myProperty;
public string MyProperty
get { return myProperty; }
if (myProperty != value)
myProperty = value;
OnPropertyChanged(nameof(MyProperty));
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
在MainWindow的代码-behind中,设置DataContext并处理焦点丢失事件:
public partial class MainWindow : Window
public MainWindow()
InitializeComponent();
DataContext = new ViewModel();
private void TextBox_LostFocus(object sender, RoutedEventArgs e)
var binding = BindingOperations.GetBinding(sender as TextBox, TextBox.TextProperty);
if (binding != null)
var expression = binding.GetBindingExpression(TextBox.TextProperty);
expression.UpdateSource();
在上述示例中,MyValidationRule类用于验证绑定的属性值。当TextBox失去焦点时,将通过UpdateSource()方法强制将属性值更新到ViewModel中,从而在失去焦点时触发验证。当属性更改时,ViewModel将触发PropertyChanged事件,并且绑定的ValidationRule将被调用进行验证。