按键键绑定[MVVM]

  • 本文关键字:MVVM 绑定 c# mvvm
  • 更新时间 :
  • 英文 :


我正在努力将一些快捷键绑定到我的WPF按钮。通过使用以下代码[只是一个片段-但应该足够]动态构建按钮:

// for each command defined in the database
... 
PosCommand cmd = null; // FYI: PosCommand implements ICommand
if (!string.IsNullOrEmpty(group.AssemblyPath))
{
    if (System.IO.File.Exists(group.AssemblyPath))
    cmd = (PosCommand)Activator.CreateInstance(Assembly.LoadFile(group.AssemblyPath).GetType(group.FullQualifiedName), model);
}
else
{
cmd = (PosCommand)Activator.CreateInstance(Assembly.GetExecutingAssembly().GetType(group.FullQualifiedName), model);
}
if (cmd == null)
continue;
Function function = new Function()
{
Command = cmd,
Name = group.FunctionName,
Description = group.Description,
FunctionCode = group.FunctionCode
};
...

下面是绑定到c#代码的XAML代码片段:

<itemscontrol x:name="functionList" grid.row="0" itemssource="{Binding GroupFunctions}" xmlns:x="#unknown">
    <itemscontrol.itemtemplate>
        <datatemplate>
            <groupbox header="{Binding Group}">
                <itemscontrol scrollviewer.horizontalscrollbarvisibility="Disabled" itemssource="{Binding Functions}">
                    <itemscontrol.itemspanel>
                        <itemspaneltemplate>
                            <wrappanel />
                        </itemspaneltemplate>
                    </itemscontrol.itemspanel>
                    <itemscontrol.itemtemplate>
                        <datatemplate>
                            <Button MinWidth="91" Height="50" Content="{Binding Name}" ToolTip="{Binding Description}" Command="{Binding Command}"/> 
                        </datatemplate>
                    </itemscontrol.itemtemplate>
                </itemscontrol>
            </groupbox>
        </datatemplate>
    </itemscontrol.itemtemplate>
</itemscontrol>

我试图添加一个键绑定到按钮没有任何成功?我修改了Function类,使它包含了Modifier和Key的属性,当然是每个按钮的属性。它仍然不想工作,即使我硬编码修改器和键值??

<Button.InputBindings>
    <keybinding modifiers="{Binding Mod}" key="{MyKey}" />
</Button.InputBindings>
有谁能在这件事上帮助我吗?提前感谢!

亲切的问候,

我建议使用带有自定义触发器的System.Windows.Interactivity。我在我的博客上有一个例子,是为Caliburn Micro MVVM框架做的,但我认为它是一个跨框架的解决方案。System.Windows.Interactivity.dll是Blend的一部分,但是它可以以二进制形式重新分发,它不需要任何特殊的设置,只需要一个xcopy部署就足够了。

在一天结束时,我编写了我自己的关键侦听器。我处理了KeyEventHandler:

protected override void OnInitialized(EventArgs e)
{            
    base.OnInitialized(e);
    this.AddHandler(Keyboard.KeyDownEvent, (KeyEventHandler)HandleKeyDownEvent);
}
private void HandleKeyDownEvent(object sender, KeyEventArgs e)
{
}

基本上,所有的iccommand都是在数据库中定义的,并且是动态构建的。因此,我使用CommandProperty来添加一个复杂的数据类型。在这种复杂的数据类型中,我存储了各种各样的信息,包括要使用的快捷键。因此,键侦听器等待键组合,查找并执行iccommand。

亲切的问候,

最新更新