C# 文本框失去焦点时在ViewModel中运行函数?

C# 文本框失去焦点时在ViewModel中运行函数?,c#,xaml,mvvm,C#,Xaml,Mvvm,我目前有以下代码来定义网格中的文本框(网格是基于数据填充的,因此也在DataTemplate中): / 当文本框失去焦点时,我想在ViewModel中运行一个函数。使用LostFocus属性并绑定到函数名会导致运行时错误: 只能对DependencyObject的DependencyProperty设置“绑定” 因此,我正在寻找有关如何在焦点丢失时运行ViewModel函数的详细信息。在您的ViewModel中尝试添加: //Public property public ICommand M

我目前有以下代码来定义网格中的文本框(网格是基于数据填充的,因此也在DataTemplate中):


/
当文本框失去焦点时,我想在ViewModel中运行一个函数。使用LostFocus属性并绑定到函数名会导致运行时错误:

只能对DependencyObject的DependencyProperty设置“绑定”


因此,我正在寻找有关如何在焦点丢失时运行ViewModel函数的详细信息。

在您的ViewModel中尝试添加:

//Public property
public ICommand MyCommand { get; set; }

//In the constructor 
MyCommand = new RelayCommand(DoSometing);

//Private method to handle lost focus
private void DoSometing(){
//Do someting
}
然后在xaml中调用MyCommand

LostFocus="{Binding MyCommand}"

在ViewModel中,尝试添加:

//Public property
public ICommand MyCommand { get; set; }

//In the constructor 
MyCommand = new RelayCommand(DoSometing);

//Private method to handle lost focus
private void DoSometing(){
//Do someting
}
然后在xaml中调用MyCommand

LostFocus="{Binding MyCommand}"

必须是ViewModel不幸的是,在ViewModel的构造函数中,MyCommand=new RelayCommand部分需要转到哪里。很抱歉出现文本格式问题。我收到运行时错误
System.Windows.Markup.XamlParseException:“无法在类型为“TextBox”的“AddLostFocusHandler”属性上设置“Binding”。只能在DependencyObject的DependencyProperty上设置“绑定”。
必须是ViewModel不幸的是,您的ViewModel的构造函数中的MyCommand=new RelayCommand部分需要转到哪里。很抱歉出现文本格式问题。我收到运行时错误
System.Windows.Markup.XamlParseException:“无法在类型为“TextBox”的“AddLostFocusHandler”属性上设置“Binding”。只能对DependencyObject的DependencyProperty设置“绑定”。