尝试将此样式放入您的资源字典中:
<Style TargetType="{x:Type data:DataGridCell}">
<Setter Property="ToolTip" Value="{Binding EMail}"/>
</Style>
如您在评论中要求的那样,要启用与任何属性的绑定,您需要发挥创意。我所做的是创建两个附加属性ToolTipBinding
和IsToolTipBindingEnabled
. 设置在列ToolTipBinding
上以确定工具提示,类似于Binding
确定单元格内容的属性,并且使用类似于我上面提到的样式IsToolTipBindingEnabled
设置true
在对象上。DataGridCell
然后,我编写了代码,以便在加载单元格时,将来自其父列的绑定应用于其ToolTip
属性。
这是扩展类:
public class DGExtensions
{
public static object GetToolTipBinding(DependencyObject obj)
{
return obj.GetValue(ToolTipBindingProperty);
}
public static void SetToolTipBinding(DependencyObject obj, object value)
{
obj.SetValue(ToolTipBindingProperty, value);
}
public static readonly DependencyProperty ToolTipBindingProperty =
DependencyProperty.RegisterAttached(
"ToolTipBinding",
typeof(object),
typeof(DGExtensions),
new FrameworkPropertyMetadata(null));
public static bool GetIsToolTipBindingEnabled(DependencyObject obj)
{
return (bool)obj.GetValue(IsToolTipBindingEnabled);
}
public static void SetIsToolTipBindingEnabled(
DependencyObject obj,
bool value)
{
obj.SetValue(IsToolTipBindingEnabled, value);
}
public static readonly DependencyProperty IsToolTipBindingEnabled =
DependencyProperty.RegisterAttached(
"IsToolTipBindingEnabled",
typeof(bool),
typeof(DGExtensions),
new UIPropertyMetadata(false, OnIsToolTipBindingEnabledChanged));
public static void OnIsToolTipBindingEnabledChanged(
DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
DataGridCell cell = d as DataGridCell;
if (cell == null) return;
bool nv = (bool)e.NewValue, ov = (bool)e.OldValue;
// Act only on an actual change of property value.
if (nv == ov) return;
if (nv)
cell.Loaded += new RoutedEventHandler(cell_Loaded);
else
cell.Loaded -= cell_Loaded;
}
static void cell_Loaded(object sender, RoutedEventArgs e)
{
DataGridCell cell = sender as DataGridCell;
if (cell == null) return;
var binding = BindingOperations.GetBinding(
cell.Column, ToolTipBindingProperty);
if (binding == null) return;
cell.SetBinding(DataGridCell.ToolTipProperty, binding);
// This only gets called once, so remove the strong reference.
cell.Loaded -= cell_Loaded;
}
}
XAML 用法示例:
<Window.Resources>
<Style TargetType="{x:Type tk:DataGridCell}">
<Setter
Property="dge:DGExtensions.IsToolTipBindingEnabled"
Value="True"/>
</Style>
</Window.Resources>
<Grid>
<tk:DataGrid ItemsSource="{Binding TheList}" AutoGenerateColumns="False">
<tk:DataGrid.Columns>
<tk:DataGridTextColumn
Header="PropA"
Binding="{Binding PropA}"
dge:DGExtensions.ToolTipBinding="{Binding PropB}"/>
<tk:DataGridTextColumn
Header="PropB"
Binding="{Binding PropB}"/>
</tk:DataGrid.Columns>
</tk:DataGrid>
</Grid>