C#:关于专注于 WPF 文本框的工具提示

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15884067/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 08:31:46  来源:igfitidea点击:

C#: Tooltip on Focus on WPF TextBox

c#wpftextboxtooltiponfocus

提问by Butters

Here is my code.

这是我的代码。

private void txtPassword_PasswordChanged(object sender, RoutedEventArgs e)
        {
            Boolean Capslock = Console.CapsLock;
            if (Capslock == true)
            {
                txtPassword.ToolTip = "Caps Lock is On.";
            }
        }

I'm trying to get a tooltip to show on TextChanged Event on WPF Control. The above code works fine and shows the tooltip with the above text when I move my mouse over the txtPassword control if Caps Lock is on.

我试图在 WPF 控件上的 TextChanged 事件上显示一个工具提示。如果 Caps Lock 处于打开状态,当我将鼠标移到 txtPassword 控件上时,上面的代码工作正常并显示带有上述文本的工具提示。

But I'm looking for something that will show the tooltip when you start typing regardless of mouse over txtPassword Control or not. Like when the txtPassword Control is focused or something similar

但是我正在寻找一些东西,当您开始输入时,无论鼠标是否悬停在 txtPassword Control 上,都会显示工具提示。就像当 txtPassword Control 被聚焦或类似的时候

Any help will be appreciated.

任何帮助将不胜感激。

回答by Dom

You might want to consider using a PopUpfor this.

您可能需要考虑为此使用PopUp

XAML:

XAML:

<TextBox x:Name="txtPassword" Height="30" Width="100" TextChanged="txtPassword_TextChanged" ></TextBox>
<Popup x:Name="txtPasswordPopup" Placement="Top" PlacementTarget="{Binding ElementName=txtPassword}" IsOpen="False">
    <TextBlock x:Name="PopupTextBlock" Background="Wheat">CAPSLOCK IS ON!</TextBlock>
</Popup>

Code-Behind:

代码隐藏:

private void txtPassword_TextChanged(object sender, TextChangedEventArgs e)
    {
        Boolean Capslock = Console.CapsLock;
        if (Capslock == true)
        {
            PopupTextBlock.Text = "Caps Lock is On.";
            txtPasswordPopup.IsOpen = true;
        }
        else
        {
            txtPasswordPopup.IsOpen = false;
        }
    }

回答by user1064519

you need to use a tooltip control and set StaysOpen and IsOpen properties to true, this caueses the tooltip to stay open till you will close it by IsOpen =false (maybe on lostFocus) here is the code:

您需要使用工具提示控件并将 StaysOpen 和 IsOpen 属性设置为 true,这会导致工具提示保持打开状态,直到您通过 IsOpen =false(可能在 lostFocus 上)关闭它,这里是代码:

 private void TextBox_GotFocus(object sender, RoutedEventArgs e)
    {
         Boolean Capslock = Console.CapsLock;
         if (Capslock == true)
         {
             ToolTip toolTip = new ToolTip();
             toolTip.Content = "Caps lock is on";
             toolTip.StaysOpen = true;
             toolTip.IsOpen = true;

             (sender as TextBox).ToolTip = toolTip;
         }
    }