我有一个WPF ComboBox,它处于数据模板中(列表框中有很多个ComboBox),我想处理回车键的操作。如果这是一个按钮那就容易了 - 我可以使用命令(Command) + 相对绑定路径(Relative binding path)等。不幸的是,我不知道如何使用Command来处理按键事件,或者如何从模板设置事件处理程序。 有什么建议吗?
我有一个WPF ComboBox,它处于数据模板中(列表框中有很多个ComboBox),我想处理回车键的操作。如果这是一个按钮那就容易了 - 我可以使用命令(Command) + 相对绑定路径(Relative binding path)等。不幸的是,我不知道如何使用Command来处理按键事件,或者如何从模板设置事件处理程序。 有什么建议吗?
您可以在使用模板的同时,使用EventSetter:
<Style TargetType="{x:Type ListBoxItem}">
<EventSetter Event="MouseWheel" Handler="GroupListBox_MouseWheel" />
<Setter Property="Template" ... />
</Style>
<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);
}
}
}
}
public class MyTextbox : TextBox
{
private void OnKeyDown(object sender, KeyEventArgs e)
{
e.Handled = true;
//...
return;
}
private void OnGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
//E.g. delete the content when focused
e.Handled = true;
this.Text = null;
return;
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
this.GotKeyboardFocus += OnGotKeyboardFocus;
this.KeyDown += OnKeyDown;
}
}
protected override void OnGotKeyboardFocus(System.Windows.Input.KeyboardFocusChangedEventArgs e)
{
e.Handled = true;
this.Text = null;
return;
}