WPF TabItem 失去焦点事件

编程入门 行业动态 更新时间:2024-10-28 00:23:57
本文介绍了WPF TabItem 失去焦点事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我的标题上有带有 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):

目标的焦点设置为真目标应该是可命中测试的.目标的背景不应为空.

将事件处理程序添加到 PreviewMouseDown 事件(注意:不是 MouseDown)以响应鼠标点击.如果你除了 3 步,你的应用程序只会对 TAB 键做出反应. Focusable of the target is set as true The target should be hit testable. Background of the target should not be null.

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屋!

更多推荐

[db:关键词]

本文发布于:2023-05-01 11:33:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1408775.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:事件   焦点   WPF   TabItem

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!