我想要处理LostFocus事件的TextBox来执行一些操作。但是,如果TextBox失去了焦点,我也不想执行该操作,因为单击了特殊的Button (打开OpenFileDialog)或捕捉了Key.Enter。当按下Key.Enter时,首先引发KeyDown事件。这里我的KeyDown事件处理程序
public void TextBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
if (e != null && sender != null)
if (e.Key == System.Windows.Input.Key.Enter && !String.IsNullOrWhiteSpace(((TextBox)sender).Text))
{
e.Handled = true;
isEnterClicked = true;
((System.Windows.Controls.TextBox)sender).Visibility = System.Windows.Visibility.Collapsed;
}
}按下Key.Enter后,TextBox.Visibility将被更改,此操作符将引发LostFocus事件。
public void TextBox_LostFocus(object sender, RoutedEventArgs e)
{
try
{
if (!isEnterClicked)
{
DependencyObject dob = (DependencyObject)sender;
while ( !(dob is ItemsControl))
{
dob = VisualTreeHelper.GetParent(dob);
}
dynamic myCmd = dob.GetValue(Control.DataContextProperty);
myCmd.SomeCommand.Execute(((TextBox)sender).GetValue(Control.DataContextProperty));
}
}
finally
{
isEnterClicked = false;
}
}LostFocus处理程序首先观察isEnterPressed是否等于false,它的平均值,TextBox失去焦点并不是因为按下enter。SomeCommand将删除一些绑定到TextBox的项,然后它将消失。
Q:所以,如何对Button.Click事件做同样的处理?
首先,在 Button点击之前,TextBox失去了焦点。同样的方式是不可接受的。Button.Focusable="False"、创建新的ControlTemplate或处理Timer.Elapsed事件都不能满足我的要求。
发布于 2011-07-20 10:58:04
如果我正确理解了问题,尝试检查按钮是否有焦点,如果是,不要在文本框丢失焦点事件中执行操作。如果Iam正确的按钮应该集中在文本框丢失焦点事件之前。
if (!isEnterClicked && !button.Focused)
{
//do stuff
}https://stackoverflow.com/questions/6759810
复制相似问题