Search code examples
c#.netwinformslocalizationtooltip

Button tooltip not getting localized


I have an extended button class as follows;

class ExtendedButton : Button
{
    private ToolTip _tooltip = new ToolTip();

    public ExtendedButton()
    {
        _tooltip.SetToolTip(this, StringResources.MyLocalizedTooltipString);
    }
}

In above code, 'StringResources.MyLocalizedTooltipString' contains strings for various languages. But when I change thread culture, tooltip text does not get changed. How to achieve that? Any help would be appreciated.


Solution

  • It's normal. SetToolTip method accepts string and it will show the text that extracted from resource based on the current culture when calling SetToolTip and changing the culture at run-time will not have any impact on it. So here since setting tooltip is performed in constructor of your button, then the culture of thread at that moment will be used.

    If you want your tooltip dynamically use the current culture automatially, as an option you can set a dummy text as tooltip (to enable the tooltip) and then handling Popup event of tooltip, assign the localized value to the tooltip:

    class ExtendedButton : Button
    {
        private ToolTip _tooltip = new ToolTip();
    
        public ExtendedButton()
        {
            _tooltip.Popup += new PopupEventHandler(_tooltip_Popup);
            _tooltip.SetToolTip(this, "DUMMYTEXT");
        }
    
        void _tooltip_Popup(object sender, PopupEventArgs e)
        {
            if (_tooltip.GetToolTip(this) != StringResources.MyLocalizedTooltipString)
                _tooltip.SetToolTip(this, StringResources.MyLocalizedTooltipString);
        }
    }
    

    Note: If your goal is not making the tooltip dynamically localizable and you only want a localizable tooltip, the way Localizable property of Form works, go to designer of your ExtendedButton component and set Localizable property to true and then use different tooltip texts for different cltures.

    But keep in mind, the value can not be changed dunamically at runtime, after the component is created.

    Here is an example:

    Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("fa-IR");
    var f = new Form();
    f.Controls.Add(new ExtendedButton());
    f.Show();