简体   繁体   English

动态将按键绑定添加到按钮

[英]Dynamically add KeyBindings to Buttons

As you can see on this question I need dynamic buttons. 正如你可以看到在这个问题我需要动态按钮。 Now I need to add some KeyBinding s to those buttons. 现在,我需要向这些按钮添加一些KeyBinding The shortcuts are stored in my Product class as string. 快捷方式以字符串形式存储在我的Product类中。 I tried using a ListBox / ListView like I used for creating my buttons, but I can't add KeyBindings there. 我尝试使用ListBox / ListView就像创建按钮一样,但是无法在其中添加KeyBindings。

Example: Button is bound to object "Coke" where "C" is the shortcut. 示例:按钮绑定到对象“可乐”,其中“ C”是快捷方式。 If I click on this button my OrderCommand command is executed and my bound object is used as its parameter. 如果单击此按钮,则将执行OrderCommand命令,并且将绑定的对象用作其参数。 The same should work if I press "C". 如果我按“ C”,同样应该起作用。

Also I need it to work with dupes, let's say I have two products with the shortcut "C", and if I press "C" not the first button is pressed. 另外,我还需要使用它来处理假面,比如说我有两个产品的快捷键“ C”,如果我按下“ C”,则不会按下第一个按钮。 Pressing "C" will switch between those two buttons and if I press enter, the Command will be executed. 按“ C”将在这两个按钮之间切换,如果我按Enter,则将执行Command

You can restyle buttons inside the list control to set their InputBindings 您可以在列表控件中重新设置按钮样式,以设置其InputBindings

<ListBox ItemsSource={Binding Buttons}>
    <ListBox.Resources>
         <Style x:Key="{x:Type Button}" BasedOn="{x:Type Button}">
              <Setter Property="Button.InputBindings"/>
                   <Setter.Value>
                        <KeyBinding Key="C" Command="{Binding OrderCommand}" />     
                   </Setter.Value>
              </Setter>
         </Style>
    </ListBox.Resources>
</ListBox>

you have to define the Keybinding for the command in DataContext that you can do like below: 您必须在DataContext中定义命令的键绑定,您可以像下面这样进行操作:

<Window.InputBindings>
  <KeyBinding Key="C" Command="{Binding OrderCommand}" />
</Window.InputBindings>

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

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