WPF提示工具可见性

31

如何确保按钮禁用时仅显示按钮工具提示?

我可以将工具提示的可见性绑定到什么上?


当它被“禁用”时?- 你是指它没有被禁用吗? - 4imble
11
展示一个提示框来解释为什么无法触摸此按钮可能是有意义的。如果David的意图是这样,我认为这非常有意义。 - reuscam
1
是的,我想是这样,我并不挑剔。我只是真的很感兴趣 :) - 4imble
1
我确实是禁用了。正如reuscam建议的那样,工具提示是为了解释按钮为什么被禁用。 - David Ward
4个回答

46

2
对于任何想要做与我相同事情的人,我已经在答案中发布了按钮的完整xaml。感谢您的帮助。 - David Ward

37

这是Button的完整XAML代码(基于@Quartermeister的答案)。

<Button 
  x:Name="btnAdd" 
  Content="Add" 
  ToolTipService.ShowOnDisabled="True" 
  ToolTipService.IsEnabled="{Binding ElementName=btnAdd, Path=IsEnabled, Converter={StaticResource boolToOppositeBoolConverter}}" 
  ToolTip="Appointments cannot be added whilst the event has outstanding changes."/>

12

你也可以使用一个简单的触发器来完成。只需将以下代码片段放入一个窗口中即可。

<StackPanel Orientation="Vertical" HorizontalAlignment="Center" VerticalAlignment="Center">
    <CheckBox Name="chkDisabler" Content="Enable / disable button" Margin="10" />
    <Button Content="Hit me" Width="200" Height="100" IsEnabled="{Binding ElementName=chkDisabler, Path=IsChecked}">
        <Button.Style>
            <Style TargetType="{x:Type Button}">
                <Setter Property="ToolTipService.ShowOnDisabled" Value="true" />
                <Setter Property="ToolTip" Value="{x:Null}" />
                <Style.Triggers>
                    <Trigger Property="IsEnabled" Value="False">
                        <Setter Property="ToolTip" Value="Hi, there! I'm disabled!" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Button.Style>
    </Button>
</StackPanel>

这很方便,可以通过Style设置器查看设置ShowOnDisabled的语法。 - mungflesh
如果我正确理解这段代码,那么可以设置两个触发器来提供两个不同的工具提示,一个用于按钮禁用,另一个用于启用。 - Mike
是的 Mike,你可以添加第二个触发器用于 IsEnabled 并将其设置为 True。 - Josh

5

这是对David Ward提出的建议稍作修改后的答案。以下是完整代码:

向资源添加值转换器,格式如下:

<Window.Resources>
    <Converters:NegateConverter x:Key="negateConverter"/>
</Window.Resources>

那么请定义以下的XAML:
<Button 
  x:Name="btnAdd" 
  Content="Add" 
  ToolTipService.ShowOnDisabled="True" 
  ToolTipService.IsEnabled="{Binding RelativeSource={RelativeSource self}, Path=IsEnabled, Converter={StaticResource negateConverter}}" 
  ToolTip="Hi guys this is the tool tip"/>

值转换器长这样
[ValueConversion(typeof(bool), typeof(bool))]
  public class NegateConverter : IValueConverter
  {
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
     return  !((bool)value);
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
      throw new NotImplementedException();
    }
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接