如何将工具提示的可见性绑定到textblock中的文本?

时间:2012-11-01 13:30:07

标签: wpf xaml tooltip

<DataGrid x:Name="dgRecords1"
          CanUserAddRows="False" IsReadOnly="True"
          ColumnHeaderStyle="{DynamicResource DataGridColumnHeaderStyle1}"
          Style="{DynamicResource StyleDatagrid}"
          SelectionChanged="dgRecords1_SelectionChanged"
          Height="251" Width="569" Margin="41,173,168,0">
  <DataGrid.RowStyle>
    <Style TargetType="DataGridRow">
      <Setter Property="ToolTip">
        <Setter.Value>
          <Border Width="200" Height="80"
                  BorderBrush="Black" BorderThickness="1"
                  Background="AliceBlue">
            <StackPanel Orientation="Vertical">
              <StackPanel Height="30" Background="Black">
                <TextBlock Text="Email Sent To"
                           FontSize="14" FontWeight="Bold" Foreground="White"/>
              </StackPanel>
              <StackPanel>
                <TextBlock Text="{Binding SentToList}"
                           TextWrapping="Wrap" FontWeight="Bold"/>
              </StackPanel>
            </StackPanel>
          </Border>
        </Setter.Value>
      </Setter>
    </Style>
  </DataGrid.RowStyle>

在上面的代码中,

   <TextBlock TextWrapping="Wrap" FontWeight="Bold" Text="{Binding SentToList}" />

我想检查这个文本块中是否有东西,如果没有,我需要让工具提示不可见。有没有办法使用触发器来做?

1 个答案:

答案 0 :(得分:5)

您可以通过ToolTip控件包围Border,并使用从字符串转换为Visibility的binding converter将该控件的Visibility绑定到同一SentToList属性。

<Style TargetType="DataGridRow">
    <Style.Resources>
        <local:StringToVisibilityConverter x:Key="StringToVisibilityConverter"/>
    </Style.Resources>
    <Setter Property="ToolTip">
        <Setter.Value>
            <ToolTip Visibility="{Binding SentToList, Converter={StaticResource StringToVisibilityConverter}}">
                <Border>
                    ...
                </Border>
             </ToolTip>
        </Setter.Value>
    </Setter>
</Style>

转换器可能如下所示:

public class StringToVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return string.IsNullOrWhiteSpace(value as string) ? Visibility.Collapsed : Visibility.Visible;
    }

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