简体   繁体   中英

How can I make a ToolTip for a text box in WPF, Using C# not XAML

I want to make a ToolTip that appears, and then disappears after 5 seconds or when the user clicks into the text box again, but if the user move his mouse or over the text box, the tool tip shouldn't disappear earlier than 5 seconds.

Here is my code, I'm checking to prevent the user from typing these characters inside the txtName text box, and when the user writes any of these characters, it replaces them with "" and then I want to immediately show the tool tip, that should disappear after 5 seconds, but in this code, the SetShowDuration is not working, the tool tip appears and stays forever.

        private void txtName_TextChanged(object sender, EventArgs e)
    {
        if (Regex.IsMatch(txtName.Text, @"[\\/:*?""<>|]"))
        {
            string pattern = @"[\\/:*?""<>|]";
            Regex regex = new Regex(pattern);
            txtName.Text = regex.Replace(txtName.Text, "");

            ToolTip toolTip = new ToolTip();
            toolTip.Content = @"The file name can't contain any of the following characters: \ / : * ? "" < > |";
            toolTip.IsOpen = true;
            ToolTipService.SetToolTip(toolTip, txtName);
            ToolTipService.SetShowDuration(toolTip, 1000);
        }
    }

For "customized" tooltips of this kind, I would recommended you to consider using a Popup for greater flexibility. You could use its IsOpen property to decide when you want to display and hide the "tooltip".

WPF Popup vs Tooltip

In this case, you could for example use a timer that sets the IsOpen to false after 5 seconds:

await Task.Delay(5000):
popup.IsOpen = false;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM