c# - 当 TextBox 失去焦点时在 ViewModel 中运行函数?

标签 c# xaml mvvm

我目前有以下代码在网格中定义 TextBox(网格是根据数据填充的,因此也在 DataTemplate 中):

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


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

A 'Binding' can only be set on a DependencyProperty of a DependencyObject



因此,我正在寻找有关在失去焦点时如何运行 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}"

关于c# - 当 TextBox 失去焦点时在 ViewModel 中运行函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57783930/

相关文章:

xaml - 实现 ListView 的 float 操作按钮bottom_right - Xamarin.forms

c# - ScrollViewer 不适用于 StackPanel

c# - 未能成功地将我的 ViewModel 数据公开给我的 XAML 绑定(bind) View

c# - 将 System.Speech.Synthesis 与 Windows10 通用应用程序 (XAML-C#) 结合使用

c# - sizeof() 等同于引用类型?

c# - List<String> 到 List<Object> C#

mvvm - Prism正确处理ViewModel集合

c# - 获取连接的 USB 设备的端口名称

wpf - 可调整大小的 WPF 网格根据实际大小在行和列之间插入空行

c# - 获取对 View 中单击项的引用