WPF Binding to Tooltip

前端 未结 4 1342
误落风尘
误落风尘 2021-02-13 01:37

Not sure whats doing here, but the binding works for the label in the data template but not the tool tip. Any help will be appreciated.

                    

        
4条回答
  •  梦毁少年i
    2021-02-13 01:58

    I also had problems with bindings in the tooltip, since the tooltip was defined as a resource. I solved the problem by creating an event handler for ToolTipOpening event. In the handler function you can then access the DataContext of the displayed UI element and set the DataContext of the Tooltip.

    This was my XAML:

    
    

    and this was my code handler:

    void Item_ToolTipOpening(object sender, ToolTipEventArgs e)
        {
            if (sender as FrameworkElement == null)
                return;
            ToolTip tooltip = (ToolTip) FindResource("MailItemToolTip");
            if ((sender as FrameworkElement).DataContext is LinkItem)
                tooltip.DataContext = ((sender as FrameworkElement).DataContext as LinkItem).ParentItem as MailItem;
            else if ((sender as FrameworkElement).DataContext is AttachmentItem)
                tooltip.DataContext = ((sender as FrameworkElement).DataContext as AttachmentItem).ParentItem as MailItem;
            (sender as FrameworkElement).ToolTip = tooltip;
        }
    

    Note that the ToolTip has to be set (at least to some value), otherwise the ToolTipOpening event is not called.

提交回复
热议问题