c# - 将 InputGestureText 显示为 Button 的工具提示

标签 c# wpf xaml tooltip routed-commands

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

最佳答案

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>

关于c# - 将 InputGestureText 显示为 Button 的工具提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35341543/

相关文章:

c# - 尝试绑定(bind) XAML 数据时出现异常

xaml - 如何在 Xamarin 的内容 View 中设置背景图像

c# - 在 C# 中创建仅适用于特定类型的通用函数

c# - 带有 yield 返回的异步任务<IEnumerable>?

WPF TextBlock Padding 正在切断文本

c# - 从ViewModel更改WPF样式

c# - EntitySet.Last()不是最新添加的元素?

c# - 如何在扫描图像中搜索著名标志?

c# - 网格列中的控件不考虑列的大小

c# - MVVM:自定义 devexpress propertyGridControl