我在数据模板中有WPF ComboBox(列表框中有很多组合框),我想处理输入按钮。如果它是例如它将很容易一个按钮 - 我会使用Command + Relative绑定路径等。不幸的是,我不知道如何使用Command处理按键或如何从模板设置事件处理程序。 有什么建议吗?

有帮助吗?

解决方案 2

我通过使用通常的事件处理程序解决了我的问题,我在其中浏览可视树,找到相应的按钮并调用它的命令。 如果其他人有同样的问题,请发表评论,我会提供更多实现细节。

UPD

这是我的解决方案:

我在可视树中搜索按钮,然后执行与按钮关联的命令。

View.xaml:

<ComboBox KeyDown="ComboBox_KeyDown"/>
<Button Command="{Binding AddResourceCommand}"/>

View.xaml.cs:

private void ComboBox_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter)
    {
        var parent = VisualTreeHelper.GetParent((DependencyObject)sender);
        int childrenCount = VisualTreeHelper.GetChildrenCount(parent);

        for (int i = 0; i < childrenCount; i++)
        {
            var child = VisualTreeHelper.GetChild(parent, i) as Button;
            if (null != child)
            {
                child.Command.Execute(null);
            }
        }
    }
} 

其他提示

您可以在设置模板的样式中使用EventSetter:

<Style TargetType="{x:Type ListBoxItem}">
      <EventSetter Event="MouseWheel" Handler="GroupListBox_MouseWheel" />
      <Setter Property="Template" ... />
</Style>

本文提供了一种将 Event 路由到 Command

的方法

http://nerobrain.blogspot.nl/2012/ 01 / WPF的事件到command.html

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top