开发者

LostFocus handling issue

I want to handle LostFocus event of TextBox to perform some actions. But I'm also wouldn't want to perform that actions if TextBox lost it focus because special Button (which opens OpenFileDialog) was clicked or Key.Enter was catched. When Key.Enter was pressed, first of all KeyDown event is raised. Here my event handler of 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;
        }
}

After Key.Enter was pressed, TextBox.Visibility is changed, and this operator will raise LostFocus event.

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 handler firstly watch whether isEnterPressed equals to false, its mean, TextBox lost it开发者_开发问答 focus not because enter was pressed. SomeCommand will delete some item which was bind to TextBox, and it will disappear.

Q: So, how to do the same with Button.Click event?

First of all, BEFORE Button clicked, TextBox lost it focus. The same way is not acceptable. Button.Focusable="False", creating new ControlTemplate or handling Timer.Elapsed event do not satisfy my requirements.


If I understood problem correctly, try to check if button is focused, if so dont perform actions in textbox lostfocus event. If Iam correct button should be focused before textbox lostfocus event raised.

if (!isEnterClicked && !button.Focused)
{
    //do stuff
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜