简体   繁体   English

当TextBox失去焦点时在ViewModel中运行函数吗?

[英]Run function in ViewModel when TextBox loses focus?

I currently have the following code to define a TextBox in a grid (the grid is populated based on data, so is also inside a DataTemplate): 我目前有以下代码来在网格中定义TextBox(网格是根据数据填充的,因此也在DataTemplate内部):

<TextBox 
    MinWidth="120" 
    Text="{Binding BatchNumber, Mode=TwoWay}"
    ToolTip="Redacted" 
    IsTabStop="True"
    MaxLength="32" 
    <!-- LostFocus="TextBox_LostFocus" -->
/>

I'd like to run a function in my ViewModel when the textbox loses focus. 当文本框失去焦点时,我想在ViewModel中运行一个函数。 Using the LostFocus property, and binding to a function name, causes a runtime error of: 使用LostFocus属性并绑定到函数名称会导致以下运行时错误:

A 'Binding' can only be set on a DependencyProperty of a DependencyObject 只能在DependencyObject的DependencyProperty上设置“绑定”

As such, I'm looking for details on how to run a ViewModel function when focus is lost. 因此,我正在寻找有关失去焦点时如何运行ViewModel函数的详细信息。

In your ViewModel try to add: 在您的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
}

Then call MyCommand in your xaml. 然后在您的xaml中调用MyCommand。

LostFocus="{Binding MyCommand}"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM