提交对 ViewModel 中当前 WPF GUI 元素的编辑

Commit edit of current WPF GUI element in ViewModel

我使用键绑定调用保存方法。但是,如果我当前在文本框中并更改了值,则不会提交。

保存发生在文本框提交更改之前,保存的数据不包含更改。

如何提交当前 GUI 元素的编辑模式?

InputBindings.Add(new KeyBinding(((MainViewModel)this.DataContext).SavePartCommand, new KeyGesture(Key.S, ModifierKeys.Control)));


class PartViewModel
{
    public override void ExecuteSaveCommand() 
    {
         //commit the edit mode of current GUI element 

         //do the saving
    }
}

一种不太优雅的方法是将绑定设置为在更改时立即更新,而不仅仅是在失去焦点时

<TextBox Text="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />

您必须对控件中可以保持编辑模式的每个 GUI 元素执行此操作。