David David - 28 days ago 11
C# Question

WPF & XAML: DisplayToolTipPath

ListBox control has property

DisplayMemberPath
that specifies what is showed inside ListBoxItem(s).

Unfortunately, I miss property
DisplayToolTipPath
. Do you know some simple way how to simulate this situation in XAML (I preffer XAML solution to code).

My attempt is something like this:

<ListBox>
<ListBox.Resources>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="ToolTip" Value="{Binding ??? {Binding ToolTipMemberPath}}" />
</Style>
</ListBox.Resources>
</ListBox>

Answer

Try

<Style TargetType="{x:Type ListBoxItem}">
    <Setter Property="ToolTip" Value="{Binding Path=DataContext.ToolTipMemberPath, RelativeSource={RelativeSource Self}}" />
</Style>

With ToolTipMemberPath the desired prop on your ListBoxItem Class.

EDIT

The easiest solution when TooltipMemberPath is a parent property would involve a Converter:

<Style TargetType="{x:Type ListBoxItem}">
    <Setter Property="ToolTip">
        <Setter.Value>
            <MultiBinding Converter="{StaticResource PathToTooltipConverter}">
                <Binding RelativeSource="{RelativeSource Self}"/>
                <Binding Path="TooltipMemberPath" 
                         RelativeSource="{RelativeSource AncestorType={x:Type CustomListBoxControl:CustomListBox}}"/>
            </MultiBinding>
        </Setter.Value>
    </Setter>
</Style>

IMultiValueConverter

public class PathToTooltipConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        ListBoxItem item = values[0] as ListBoxItem;
        string tooltipMemberPath = values[1] as string;

        if (tooltipMemberPath == null)
            return null;

        MyListBoxItemClass itemClass = (MyListBoxItemClass)item.DataContext;
        return itemClass.GetType().GetProperty(tooltipMemberPath).GetValue(itemClass, null);
    }

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