0
votes

Unable to set the parent datacontext for datatemplate tooltip.

Below is the xaml code. Just once combo box and in the combobox datatemplate added textbox.

Xaml

<UserControl x:Class="WpfApplication1.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             Name="UC"
             d:DesignHeight="50" d:DesignWidth="200">
    <Grid>
        <ComboBox Width="200" Height="50" ItemsSource="{Binding Coll}">
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Length}">
                        <TextBlock.ToolTip>
                            <ToolTip Content="{Binding Path=DataContext.ToolTipValue, 
                                                       RelativeSource={RelativeSource FindAncestor, 
                                                       AncestorType={x:Type UserControl}}}"/>
                        </TextBlock.ToolTip>
                    </TextBlock>
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>
    </Grid>
</UserControl>

ViewModel

    private List<string> _coll;

    public List<string> Coll
    {
        get { return _coll; }
        set { _coll = value; OnPropertyChanged(); }
    }

    private string _ToolTipValue;

    public string ToolTipValue
    {
        get { return _ToolTipValue; }
        set { _ToolTipValue = value; OnPropertyChanged(); }
    }

    public ViewModel()
    {
        _coll = new List<string>(){ "1", "2", "3"};
        _ToolTipValue = "Demo";
    }

Can you please help me why DataContext is not set.

Is it binding issue?

1
you need to call ToolTipValue = "something to trigger it's setter and OnPropertyChanged, you should not interact with the private properties.Felix D.
Can you please elaborate it, I set value to private field in constructor. It's working fine for combox itemsourcesuperuser
Agreed, it works. imagine you changing the values later. the private property won't update property changed !Felix D.
can u add a little more xaml pls. At least the usercontrol you are refering toFelix D.
Just i am trying sample demo, But couldn't set tooltip textsuperuser

1 Answers

1
votes

if you don't need any special things try not to nest the tooltip:

<TextBlock ToolTip="{Binding DataContext.ToolTipValue, 
                     RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}"
           Text="{Binding Length}"/>