Search code examples
c#wpfxamltooltip

How to set tooltip dynamically for textblock in dataTemplate?


Each entry in my listbox has the template below. How do I programmatically set the tooltip for Price and for ProductName? What ids can I use? Please note that I want to distinguish the 2 items: Price and ProductName and display a different tooltip for each even though they belong to the same entry in listbox.

As you see, setting the tooltip in xaml (as seen for Price below) is straightforward. But I need the flexibility of setting it dynamically. Thanks.

<DataTemplate>
    <DockPanel >
        <TextBlock DockPanel.Dock="Left" Text = "{Binding ProductName}" />
        <TextBlock Text="   " />
        <TextBlock Text = "{Binding Price}" ToolTip="Price" />
    </DockPanel>
</DataTemplate>

Solution

  • You can bind the tooltip (you can bind almost any property) so that when you assign to the property the UI will update. Your best bet would be to make a property somewhere (like the object that has your Price property) and bind to that critter. Just make sure that you use a DependencyProperty or use INotifyPropertyChanged.

    <DataTemplate>
        <DockPanel>
           <TextBlock DockPanel.Dock="Left" Text = "{Binding ProductName}" />
           <TextBlock Text="   " />
           <TextBlock Text = "{Binding Price}" ToolTip="{Binding PriceTooltipProperty}" />
        </DockPanel>
    </DataTemplate>