Search code examples
c#wpfmvvmdatacontext

Wrong DataContext binding ToolTipService.IsEnabled in DataGridTextColumn


I want to display an image on hover of a DataGridTextColumn with use of ToolTip. It's working great so far but I need to disable the ToolTip if there is no image available.

This is my Code so far:

<DataGridTextColumn Header="{lex:Loc material}" Binding="{Binding Material}" Width="Auto" MinWidth="75" ToolTipService.IsEnabled="{Binding ProductImageExists}" ToolTipService.ShowDuration="99999" ToolTipService.InitialShowDelay="0">
<DataGridTextColumn.CellStyle>
    <Style TargetType="DataGridCell" BasedOn="{StaticResource MaterialDesignDataGridCell}">
        <Setter Property="ToolTip">
            <Setter.Value>
                <Image Source="{Binding ProductImage}" Width="250" />
            </Setter.Value>
        </Setter>
    </Style>
</DataGridTextColumn.CellStyle>

Result of output

System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=ProductImageExists; DataItem=null; target element is 'DataGridTextColumn' (HashCode=42700980); target property is 'IsEnabled' (type 'Boolean')

Why does the tooltip has another datacontext? How can I set it to the correct one?


Solution

  • You can't bind a property of the DataGridTextColumn to ProductImageExists because it doesn't inheirt any DataContext.

    You could use a DataTrigger in the Style that binds to ProductImageExists and sets the ToolTip property to null if it returns false though:

    <DataGridTextColumn Header="{lex:Loc material}" 
                        Binding="{Binding Material}" Width="Auto" MinWidth="75" 
                        ToolTipService.ShowDuration="99999" ToolTipService.InitialShowDelay="0">
        <DataGridTextColumn.CellStyle>
            <Style TargetType="DataGridCell" BasedOn="{StaticResource MaterialDesignDataGridCell}">
                <Setter Property="ToolTip">
                    <Setter.Value>
                        <Image Source="{Binding ProductImage}" Width="250" />
                    </Setter.Value>
                </Setter>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding ProductImageExists}" Value="False">
                        <Setter Property="ToolTip" Value="{x:Null}" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </DataGridTextColumn.CellStyle>
    </DataGridTextColumn>