Gene S
Gene S

Reputation: 2793

Display custom width tooltip in WPF DataGrid

I am displaying a tooltip in a WPF DataGrid but I want to customize the width of it so it is no larger then the size of the cell containing the data. I tried setting the Path to "Width" and "ActualWidth" but it ignores them both. What am I doing wrong?

<DataGridTextColumn Binding="{Binding Description}" Header="Message" Width="*">
<DataGridTextColumn.ElementStyle>
    <Style TargetType="{x:Type TextBlock}">
        <Setter Property="TextTrimming" Value="CharacterEllipsis" />
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter Property="ToolTipService.ShowDuration" Value="60000" />
                <Setter Property="ToolTip">
                    <Setter.Value>
                        <TextBlock TextWrapping="Wrap"
                            Width="{Binding RelativeSource={RelativeSource AncestorType=DataGridCell}, Path=ActualWidth}"
                            Text="{Binding Description}" />
                    </Setter.Value>
                </Setter>
            </Trigger>
        </Style.Triggers>
    </Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>

Upvotes: 1

Views: 1278

Answers (1)

peter
peter

Reputation: 13501

I found this which helps explain why it isn't working,

How can I turn binding errors into runtime exceptions?

So you add this,

public class BindingErrorListener : TraceListener
{
    private Action<string> logAction;
    public static void Listen(Action<string> logAction)
    {
        PresentationTraceSources.DataBindingSource.Listeners
            .Add(new BindingErrorListener() { logAction = logAction });
    }
    public override void Write(string message) { }
    public override void WriteLine(string message)
    {
        logAction(message);
    }
}

And add this to your code behind,

BindingErrorListener.Listen(m => MessageBox.Show(m));
InitializeComponent();

So basically the result of that is your code has a binding error in it,

Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.DataGridCell', AncestorLevel='1''. BindingExpression:Path=ActualWidth; DataItem=null; target element is 'TextBlock' (Name=''); target property is 'Width' (type 'Double')

The binding error occurs before you hover over the DataGridTextColumn, so I am wondering if the binding is being created before the TextBox is being added to the visual tree, so it doesn't have an ancestor etc.

So far this tells you why the problem exists, but I cannot find a solution.

Upvotes: 1

Related Questions