Dynamic tooltip with textblock in WPF

3.9k views Asked by At

i'm have some trouble with tooltip in textblock wpf .

After i completed 1 task and if task is error i want update error info with tooltip . But tooltip never show when completed . Please help me . Thanks

Here my code C# code

if (status == "Error")
            {
                LogCreateSite item = (LogCreateSite)gridLog.Items[rowIndex];
                item.ErrorInfo = "Error";
                DataTemplate template = cellTitle.ContentTemplate;
                Canvas canvas = (Canvas)template.LoadContent();
                TextBlock txtError = (TextBlock)canvas.Children[1];
                ToolTip toolTip = new ToolTip();
                toolTip.Content = "asdfasdf";
                txtError.ToolTip = toolTip;
                txtError.UpdateLayout();
            }

And my Xaml :

<DataTemplate x:Key="error">
            <Canvas Margin="10,15,0,0">
                <!--<Ellipse Fill="#FF5050" Width="12" Height="12">
                </Ellipse>-->

                <Viewbox Width="16" Height="16">
                    <Frame Source="../Icon/Error_16.xaml" />
                </Viewbox>

                <TextBlock Text="Error" Margin="25,-3,0,0">
                </TextBlock>
                <TextBlock Cursor="Hand" Name="txtErrorInfo" ToolTip="{Binding ErrorInfo, Mode=OneWay,UpdateSourceTrigger=PropertyChanged}" FontSize="14" Text="?" Margin="60,-3,0,0" FontWeight="Bold" Foreground="Blue">

                </TextBlock>
            </Canvas>
        </DataTemplate>
2

There are 2 answers

4
Prajwal On

You need to do binding for tool tip to show the error/message to user.

Please go thru this tutorial for wpf binding. Introduction to WPF data binding from WPF-tutorial.

your XAML should be like this for a proper binding.

Name="txtErrorInfo" ToolTip="{binding path=error mode=OneWay UpdateSourceTrigger=PropertyChanged}" 

It is required to mention mode and UpdateSourceTrigger when you are changing the property which should be shown to user.

3
AnjumSKhan On

Correcting your code, see this sample for how to show ToolTip from code :

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        ToolTip t = new ToolTip();
        t.Content = DateTime.Now.ToString();
        t.IsOpen = true;
        t.PlacementTarget = txtError;
        t.Placement = System.Windows.Controls.Primitives.PlacementMode.Bottom;

        txtError.ToolTip = t;
    }