DataTemplate中的事件处理程序 [英] Event handler in DataTemplate

查看:180
本文介绍了DataTemplate中的事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

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



UPD / p>

这是我的解决方案:



我在视觉树中搜索一个按钮,而不是执行与按钮相关的命令。



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);
}
}
}
}


I have WPF ComboBox inside a data template (a lot of comboboxes in listbox) and I want to handle enter button. It would be easy if it was e.g. a button - I would use Command + Relative binding path etc. Unfortunately, I have no idea how handle key press with a Command or how to set event handler from template. Any suggestions?

解决方案

I've solved my problem by using a usual event handler where I walk through the visual tree, find corresponding button and call it's command. If anybody else has the same problem, please post a comment and I'll provide more details of realization.

UPD

Here is my solution:

I search the visual tree for a button and than execute command associated with button.

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);
            }
        }
    }
} 

这篇关于DataTemplate中的事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆