简体   繁体   中英

How to add tooltip to all controls in a form programmatically - WPF, C#?

在此处输入图片说明

I have a WPF Form with different types of control like textboxes, textblocks, combobox, buttons etc. I need to add tooltips to each of these controls dynamically using C#, so that they can display the following information:

  1. X and Y position
  2. TabIndex.

I do the code as below for each control as below (code for textbox for now):

 foreach (Control ctrl in grd.Children)
        {
            if (ctrl.GetType().ToString() == "System.Controls.TextBox")
            {
                tbox = ctrl as TextBox;
                Point p = Mouse.GetPosition(tbox);
                tbox.ToolTip =p.X + " " + p.Y + " \n " + tbox.TabIndex ;
            }
        }

But this is not working. Any thoughts?

First of all your type checking is just plain evil.

 if (ctrl.GetType().ToString() == "System.Controls.TextBox")

Change it to

 if (ctrl is TextBox)

or even better

var textbox = ctrl as TextBox;
if(textbox != null)

Note that in wpf TextBox is in System.Windows.Controls namespace.

Your loop will only check first level in Visual Tree if you want to have other containers, templates anything that groups controls then you have to traverse the tree. See this for how to do it.

try with this code

var controls = grd.Children.OfType<TextBox>();

foreach(var control in controls)
{
   Point point = Mouse.GetPosition(control);
   control.ToolTip = point.X + " " + point.Y + " \n " + control.TabIndex ;
}

Let's suppose you do MVVM.

Then you probably have a ViewModel class. In that class, you can define a dynamic string for each control, just where you define your controls.

In the XAML, you just define the tooltip, eg

<Button Content="Submit">
    <Button.ToolTip>
        <ToolTip>
            <StackPanel>
                <TextBlock FontWeight="Bold">Submit Request</TextBlock>
                <TextBlock>Submits the request to the server.</TextBlock>
            </StackPanel>
        </ToolTip>
    </Button.ToolTip>
</Button>

The Textblock text can be delivered in your ViewModel and Binding will get them to your View.

I suppose that your ViewModel also knowns on which Tab your controls are.

For more information on Tooltips, there is the WPFTutorials site WPF Tutorial on Tooltip Controls

For more information on MVVM, there is a quick tutorial here: MSDN on MVVM

Your type checking is wrong (namespace!). Try this:

foreach (var ctrl in grd.Children)
        {
            if (ctrl is TextBox)
            {
                tbox = ctrl as TextBox;
                Point p = Mouse.GetPosition(tbox);
                tbox.ToolTip =p.X + " " + p.Y + " \n " + tbox.TabIndex ;
            }
        }

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