【问题标题】:Adding a list of key bindings添加键绑定列表
【发布时间】:2016-04-20 12:48:08
【问题描述】:

在我的 WPF MVVM 应用程序中,每个模型视图都包含一个按钮列表。哪些对该用户控件有效。

private List<myButton> _buttons;

我是这样显示它们的:

 <ItemsControl ItemsSource="{Binding buttons}" >
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Horizontal"/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemTemplate>
                <DataTemplate>                    
                    <Button   Width="100" Height="40" VerticalAlignment="Top" Margin="5,5,5,5" Command="{Binding command}"  Content="{Binding name}" />
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>

效果很好。

现在我想做的是在我的一些按钮上进行键绑定保存,例如 cntr + s。

如何为某些按钮添加键绑定。从我目前发现的情况来看,你会做这样的事情

<Window.InputBindings>
    <KeyBinding Key="Z" Modifiers="Ctrl" Command="{StaticResource MyCommand1}" />
    <KeyBinding Key="H" Modifiers="Alt" Command="{StaticResource MyCommand2}" />
</Window.InputBindings>

我尝试将其添加为列表,但根本不起作用。必须有一种方法可以为我的某些按钮构建键绑定。

【问题讨论】:

标签: c# wpf mvvm


【解决方案1】:

我明白了!

问题是输入绑定是一个窗口的东西而不是用户控制的东西。是的,我是 WPF 的新手。

通过将以下内容添加到 Mainwindow.xml,它将触发当前选择的用户控件的 savecommand。

<Window.InputBindings>
    <KeyBinding  Key="s" Modifiers="Ctrl" Command="{Binding ElementName=ListBoxMenu, Path=SelectedItem.SaveCommand }" />
</Window.InputBindings>

如果用户控件/模型视图所调用的内容没有保存命令,则它什么也不做。

【讨论】:

  • 是的,它确实可以,而且如果用户控件没有 SaveCommand 方法,我不会收到错误消息
  • 好的,太好了!谢谢! - 我会尝试在我的软件上复制它:p
猜你喜欢
  • 1970-01-01
  • 2018-11-02
  • 2014-10-31
  • 1970-01-01
  • 1970-01-01
  • 2015-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多