WPF TabItem 失去焦点事件 [英] WPF TabItem lost focus event

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

问题描述

我的标题上有带有 TextBox 的 tabItem.我使用 LostFocus 和 MouseDoubleClick 事件将文本设置为 TextBox.

I have tabItems with TextBox on their headers. I use LostFocus and MouseDoubleClick events to set the text to the TextBox.

<TabControl>
                <TabItem Width="50">
                    <TabItem.Header>
                        <TextBox Text="text" IsReadOnly="True" LostFocus="TextBox_LostFocus" MouseDoubleClick="TextBox_MouseDoubleClick"/>
                    </TabItem.Header>
                </TabItem>
</TabControl>

    private void TextBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
        TextBox text_box = sender as TextBox;
        if (text_box == null) { return; }

        text_box.IsReadOnly = false;
        text_box.SelectAll();
    }

    private void TextBox_LostFocus(object sender, RoutedEventArgs e)
    {
        TextBox text_box = sender as TextBox;
        if (text_box == null) { return; }

        text_box.IsReadOnly = true;
    }

LostFocus 事件仅在您单击 TextBox 外部的 TabItem 标题区域或另一个 TabItem 时发生.单击选项卡项内容区域不会触发失去焦点事件.

LostFocus event happens if only you click on the TabItem header area outside the TextBox or on enother TabItem. Clicking the tab item content area doesn't fire lost focus event.

当用户单击 TextBox 外的任何区域时,如何使 TextBox 失去焦点?

How to make the TextBox to lose focus when user click any area outside the TextBox?

推荐答案

失去焦点,换句话说就是在标签页内容(目标)内获得焦点:

To lost Focus, in other word to get Focus at inside tab content(target):

  1. 目标的焦点设置为真
  2. 目标应该是可命中测试的.目标的背景不应为空.
  3. 将事件处理程序添加到 PreviewMouseDown 事件(注意:不是 MouseDown)以响应鼠标点击.如果你除了 3 步,你的应用程序只会对 TAB 键做出反应.

  1. Focusable of the target is set as true
  2. The target should be hit testable. Background of the target should not be null.
  3. Add event handler to PreviewMouseDown event(NOTE: NOT MouseDown) to react to mouse click. If you except 3 step, you application will react only to TAB key.

<TabControl>
    <TabItem Width="50">
        <TabItem.Header>
            <TextBox 
                Text="text" IsReadOnly="True" 
                LostFocus="TextBox_LostFocus"
                MouseDoubleClick="TextBox_MouseDoubleClick"/>
        </TabItem.Header>
        <Border Focusable="True" Background="Transparent" PreviewMouseDown="Border_PreviewMouseDown"/>
    </TabItem>
</TabControl>


private void Border_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    var uiElement = sender as UIElement;
    if (uiElement != null) uiElement.Focus();
}

这篇关于WPF TabItem 失去焦点事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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