4

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.

Taterhead
  • 5,763
  • 4
  • 31
  • 40
Nicke Manarin
  • 3,026
  • 4
  • 37
  • 79

1 Answers1

4

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>
Novitchi S
  • 3,711
  • 1
  • 31
  • 44
  • When I try this it gives a binding error, " 'Command' property not found on 'object' ", as soon as the Window loads. It must be a timing thing, because if I do the Binding in code in the Window's Loaded event handler, it works fine. – sidbushes Aug 05 '22 at 19:00