WPF Tooltip Visibility

2020-02-01 06:29发布

How can I ensure that a button's Tooltip is only visible when the button is disabled?

What can I bind the tooltip's visibility to?

4条回答
Emotional °昔
2楼-- · 2020-02-01 07:00

You can do it using a simple trigger also. Just place the following piece of code into a Window.

<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>
查看更多
你好瞎i
3楼-- · 2020-02-01 07:11

You will need to set ToolTipService.ShowOnDisabled to True on the Button in order to have the Tooltip visible at all when the Button is disabled. You can bind ToolTipService.IsEnabled on the Button to enable and disable the Tooltip.

查看更多
兄弟一词,经得起流年.
4楼-- · 2020-02-01 07:23

A slightly modified answer for what David Ward has proposed. Here is the full code

Add a value converter to resouces like this

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

Then define following 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"/>

The value converter looks like this

[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();
    }
  }
查看更多
Luminary・发光体
5楼-- · 2020-02-01 07:27

This is the full XAML of the Button (based on the answer of @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."/>
查看更多
登录 后发表回答