wpf DataTemplate 中的事件处理程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1800595/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Event handler in DataTemplate
提问by levanovd
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?
我在数据模板中有 WPF ComboBox(列表框中有很多组合框),我想处理输入按钮。如果它是一个按钮会很容易 - 我会使用命令 + 相对绑定路径等。不幸的是,我不知道如何使用命令处理按键或如何从模板设置事件处理程序。有什么建议?
采纳答案by levanovd
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
UPD
Here is my solution:
这是我的解决方案:
I search the visual tree for a button and than execute command associated with button.
我在可视化树中搜索按钮,然后执行与按钮关联的命令。
View.xaml:
查看.xaml:
<ComboBox KeyDown="ComboBox_KeyDown"/>
<Button Command="{Binding AddResourceCommand}"/>
View.xaml.cs:
查看.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);
}
}
}
}
回答by ezolotko
You can use the EventSetter in the style you are setting the template with:
您可以在设置模板的样式中使用 EventSetter:
<Style TargetType="{x:Type ListBoxItem}">
<EventSetter Event="MouseWheel" Handler="GroupListBox_MouseWheel" />
<Setter Property="Template" ... />
</Style>
回答by Simon Chan
This article has a way to route any Event
to Command
这篇文章有一种方法可以将任何路由Event
到Command
http://nerobrain.blogspot.nl/2012/01/wpf-events-to-command.html
http://nerobrain.blogspot.nl/2012/01/wpf-events-to-command.html