带有命令绑定的 KeyBinding 不适用于 TextBox UpdateSourceTrigger LostFocus

bli*_*eis 5 wpf key-bindings mvvm updatesourcetrigger

我正在使用 MVVM 并遇到以下问题。我的 TextBox.Text 与 UpdateSourceTrigger=LostFocus 绑定(这就是用户想要的)。我有一个带有 SaveCommand CommandBinding 的按钮 - 这有效。现在我有一个带有 Strg+S 的 KeyBinding,它也执行 SaveCommand。这就是问题所在:当我在文本框中并按 Strg+s 时,更改不在视图模型中。

有没有办法让 MVVM 命令与 KeyBinding 和 TextBox UpdateSourceTrigger=LostFocus 一起工作?

一些代码来检查问题

<Window>
<Window.InputBindings>
    <KeyBinding Key="S" Modifiers="Control" Command="{Binding SaveCommand}"></KeyBinding>
</Window.InputBindings>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>      
    <TextBox Grid.Row="0" Text="{Binding MyText1, UpdateSourceTrigger=LostFocus}" Width="100"></TextBox>
    <Button Grid.Row="1" Content="_Save" Command="{Binding SaveCommand}" IsDefault="True"></Button> 
</Grid>
</Window>

public partial class MainWindow : Window
{
    private Viewmodel _data;
    public MainWindow()
    {
        _data = new Viewmodel();
        InitializeComponent();
        this.DataContext = _data;
    }
}

public class Viewmodel : INPCBase
{
    private string _myText1;
    private Lazy<DelegateCommand> _save;

    public Viewmodel()
    {
        this._save = new Lazy<DelegateCommand>(()=> new DelegateCommand(this.SaveCommandExecute));
    }

    private void SaveCommandExecute()
    {
        MessageBox.Show(MyText1);
    }

    public string MyText1
    {
        get { return _myText1; }
        set { _myText1 = value; this.NotifyPropertyChanged(()=>MyText1);}
    }

    public ICommand SaveCommand
    {
        get { return _save.Value; }
    }
}
Run Code Online (Sandbox Code Playgroud)

bli*_*eis 1

目前我想出了以下解决方法。在我定义 KeyBindings 的用户控件/视图中,我还监听 PreviewKeyDown 事件并将焦点设置到下一个元素,例如。按下 Strg+S。

    private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.S && e.KeyboardDevice.Modifiers == ModifierKeys.Control)
        {
            var fe = Keyboard.FocusedElement as UIElement;

            if (fe != null)
            {
               fe.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
            }

        }
    }
Run Code Online (Sandbox Code Playgroud)