Keyboard events in a WPF MVVM application?

前端 未结 8 1811
情深已故
情深已故 2020-11-27 11:30

How can I handle the Keyboard.KeyDown event without using code-behind? We are trying to use the MVVM pattern and avoid writing an event handler in code-behind file.

相关标签:
8条回答
  • 2020-11-27 12:06

    Short answer is you can't handle straight keyboard input events without code-behind, but you can handle InputBindings with MVVM (I can show you a relevant example if this is what you need).

    Can you provide more information on what you want to do in the handler?

    Code-behind isn't to be avoided entirely with MVVM. It's simply to be used for strictly UI-related tasks. A cardinal example would be having some type of 'data entry form' that, when loaded, needs to set focus to the first input element (text box, combobox, whatever). You would commonly assign that element an x:Name attribute, then hook up the Window/Page/UserControl's 'Loaded' event to set focus to that element. This is perfectly ok by the pattern because the task is UI-centric and has nothing to do with the data it represents.

    0 讨论(0)
  • 2020-11-27 12:10

    Similar to karlipoppins answer, but I found it didn't work without the following additions/changes:

    <TextBox Text="{Binding UploadNumber, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
        <TextBox.InputBindings>
            <KeyBinding Key="Enter" Command="{Binding FindUploadCommand}" />
        </TextBox.InputBindings>
    </TextBox>
    
    0 讨论(0)
提交回复
热议问题