我正在尝试使用Datagrid在WPF表单的单元格上设置工具提示.
那行得通,但我不希望它弹出没有弹出文本显示的单元格.
我在这里看到过类似的问题,但是我无法使这些解决方案正常工作.
这是CellTemplate:
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Image Source="{Binding itemType}" VerticalAlignment="Center">
<ToolTipService.ToolTip>
<TextBlock Text="{Binding toolTipText}" />
</ToolTipService.ToolTip>
</Image>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
为了防止在空白的toolTipText上弹出,我添加了:
<DataGrid.Resources>
<Style x:Key="{x:Type ToolTip}" TargetType="{x:Type ToolTip}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ToolTip}">
<Border Background="Black" Visibility="{TemplateBinding Content, Converter={StaticResource StringToVisibilityConverter}}" >
<TextBlock Width="50" FontFamily="Tahoma" FontSize="11" Text="{TemplateBinding Content}" Foreground="WhiteSmoke" Padding="2" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</DataGrid.Resources>
StringToVisibilityConverter的定义如下:
public class StringToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
var stringValue = String.Empty;
if (value is System.Windows.Controls.TextBlock) stringValue = (value as System.Windows.Controls.TextBlock).Text;
else stringValue = value as string;
return string.IsNullOrWhiteSpace(stringValue) ?
Visibility.Hidden : Visibility.Visible;
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
return value;
}
}
我看到的是,当文本为空白(好)时,它不会弹出工具提示,但是当有文本时,它将弹出一个黑色矩形.
如果没有工具提示的“样式”设置,则文本框会弹出“确定”(除非它也会弹出空白文本).
当我删除
Background="Black"
在边框样式上,那么我看不到任何弹出窗口.
解决方法:
您可以使用以下celltemplate使其更简单:
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Image Source="{Binding itemType}" VerticalAlignment="Center">
<Image.ToolTip>
<ToolTip Visibility="{Binding toolTipText, Converter={StaticResource StringToVisibilityConverter}}">
<Border Background="Black" >
<TextBlock Text="{Binding toolTipText}" />
</Border>
</ToolTip>
<Image.ToolTip>
</Image>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
转换器可以简化为:
public class StringToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return String.IsNullOrEmpty(value as string) ? Visibility.Collapsed : Visibility.Visible;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}