将InputGestureText显示为Button的工具提示

时间:2016-02-11 14:08:18

标签: c# wpf xaml tooltip routed-commands

A的ButtonCommand。我希望为包含命令的每个按钮显示InputGestureTextToolTip

这就是我的尝试:

<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"/>

为简洁起见,我删除了一些元素。

我试图获得与MenuItem类似的结果。如果用户将鼠标悬停在按钮顶部,我想显示快捷方式。

1 个答案:

答案 0 :(得分:4)

MenuItem有一个属性InputGestureText,如果未设置,则会检查该项Command是否为RoutedCommand并显示该字符串对于它可以找到的第一个KeyGesture

您可以通过转换器实现相同的功能(仅适用于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;
    }
}

<强>用法:

<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>
相关问题