WPF:如何在按钮被命令禁用时显示工具提示?

我试图显示一个工具提示,而不考虑按钮的状态,但这似乎不起作用:

<Button Command="{Binding Path=CommandExecuteAction}"
ToolTip="{Binding Path=Description}" ToolTipService.ShowOnDisabled="true"
Style="{StaticResource toolbarButton}">
<Image Source="{Binding Path=Icon}"></Image>
</Button>

当按钮因Command.CanExecute返回false而被禁用时,如何显示工具提示?

注意:

ToolTipService.ShowOnDisabled=“ true ”非常有效。这在我的示例中不起作用的原因是,与按钮关联的样式重新定义了ControlTemplate,并在按钮被禁用时关闭了对按钮的点击测试(ishItTestVisible=false)。在ControlTemplate中重新启用点击测试可在禁用按钮时显示工具提示。

46248 次浏览

您可以直接在XAML元素上使用:

<Grid ToolTipService.ShowOnDisabled="True" ... >

这是一个添加到启动代码中的好方法:

ToolTipService.ShowOnDisabledProperty.OverrideMetadata(
typeof(FrameworkElement),
new FrameworkPropertyMetadata(true));

它确保对于从FrameworkElement继承的任何类,即使禁用了控件实例,也会显示工具提示。这涵盖了可以具有工具提示的所有元素。

使工具提示对所有禁用的按钮和复选框可见:

<Window.Resources>
<Style TargetType="{x:Type Button}" BasedOn="{StaticResource {x:Type Button}}>
<Setter Property="ToolTipService.ShowOnDisabled" Value="true"/>
</Style>
<Style TargetType="{x:Type CheckBox}" BasedOn="{StaticResource {x:Type CheckBox}}>
<Setter Property="ToolTipService.ShowOnDisabled" Value="true"/>
</Style>
</Window.Resources>

BasedOn=...可防止您丢失之前应用于复选框或按钮的任何其他样式。如果不对按钮或复选框使用任何其他样式,则可以删除BasedOn=..部分。