【问题标题】:Show InputGestureText as a tooltip for a Button将 InputGestureText 显示为按钮的工具提示
【发布时间】:2016-05-22 08:37:57
【问题描述】:

A 有一个 Button 和一个 Command。对于每个包含命令的按钮,我想将 InputGestureText 显示为 ToolTip

这是我尝试过的:

<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 类似的结果。如果用户将鼠标悬停在按钮上,我想显示快捷方式。

【问题讨论】:

  • 代替 Source ,你使用了 path 属性吗?

标签: c# wpf xaml tooltip routed-commands


【解决方案1】:

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多