Search code examples
c#wpfxamltooltiprouted-commands

Show InputGestureText as a tooltip for a Button


A have a Button with a Command. I want to display the InputGestureText as a ToolTip for every button that contains a command.

This is what I tried:

<n:ImageButton x:Name="NewRecordingButton" Text="Recording"        
   Command="util:Commands.NewRecording" 
   ToolTip="{Binding Source=util:Commands.NewRecording, Path=InputGestureText}" 
   ToolTipService.Placement="Top" ToolTipService.HorizontalOffset="-5"/>

I removed some elements for brevity.

I'm trying to achieve a similar result as a MenuItem. I want to display the shortcut if the user hovers the mouse on top of the button.


Solution

  • The MenuItem has a property InputGestureText, when is not set it will check whether the item's Command is a RoutedCommand and will show the display string for the first KeyGesture it can find.

    You can achieve the same thing via a converter (works only with RoutedCommand):

    public class RoutedCommandToInputGestureTextConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            RoutedCommand command = value as RoutedCommand;
            if (command != null)
            {
                InputGestureCollection col = command.InputGestures;
                if ((col != null) && (col.Count >= 1))
                {
                    // Search for the first key gesture
                    for (int i = 0; i < col.Count; i++)
                    {
                        KeyGesture keyGesture = ((IList)col)[i] as KeyGesture;
                        if (keyGesture != null)
                        {
                            return keyGesture.GetDisplayStringForCulture(CultureInfo.CurrentCulture);
                        }
                    }
                }
            }
    
            return Binding.DoNothing;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return Binding.DoNothing;
        }
    }
    

    Usage:

    <Window.Resources>
        <ResourceDictionary>
            <local:RoutedCommandToInputGestureTextConverter x:Key="RoutedCommandToInputGestureTextConverter" />
        </ResourceDictionary>
    </Window.Resources>
    <Grid>
        <Button 
            Content="Save"
            Command="Save" 
            ToolTip="{Binding Command, RelativeSource={RelativeSource Self}, Converter={StaticResource RoutedCommandToInputGestureTextConverter}}" 
            ToolTipService.ShowOnDisabled="True" />
    </Grid>