开发者

How can I achieve WPF ToolTip dynamic showing/hiding in XAML?

开发者 https://www.devze.com 2023-02-03 20:55 出处:网络
I have a 3D render which may have an entity under the mouse.I want a ToolTip with information about the entity, and can achieve this with the code below.Please note the tip is always visible when the

I have a 3D render which may have an entity under the mouse. I want a ToolTip with information about the entity, and can achieve this with the code below. Please note the tip is always visible when the mouse is over an entity and hidden if开发者_高级运维 not.

// Would like to do this in XAML - it must be possible but not sure how 
string toolTipString = null;
public void SetToolTipString()
{
    var e = _worldViewModel.MouseOverEntity;
    string newTip =  e == null ? null : e.Entity.Name;
    if (newTip != toolTipString)
    {
        toolTipString = newTip;
        if (newTip == null)
        {
            if (ToolTip != null)
            {
                ((ToolTip)ToolTip).IsOpen = false;
            }
            ToolTip = null;
        }
        else
        {
            ToolTip = new ToolTip { Content = toolTipString, IsOpen = true, StaysOpen = true };
        }
    }
}

I tried this but it didn't work:

<ToolTip
    StaysOpen="True"
    IsOpen="{Binding Path=PlacementTarget.DataContext.IsMouseOverEntity,
                     RelativeSource={RelativeSource Self}}"
    Content="{Binding Path=PlacementTarget.DataContext.MouseOverEntity.Entity.Name, 
                      RelativeSource={RelativeSource Self}}"/>

Is there a way to achieve it in XAML?


The tooltip class is actually implemented using the Popup class. You should try the same thing above with the Popup class. It might be a little tricky getting it to show where you want it (I've been having some issues, but I haven't dabbled in the class enough).

Placement Behavior

<Canvas Margin="5" Background="Red" Width="200" Height="150" >
  <Ellipse Name="ellipse1"
       Canvas.Top="60" Canvas.Left="50"
       Height="85" Width="60" 
       Fill="Black"/>

  <Popup IsOpen="{Binding Path=PlacementTarget.DataContext.IsMouseOverEntity,
                 RelativeSource={RelativeSource Self}}" PlacementTarget="{Binding ElementName=ellipse1}" Content="{Binding Path=PlacementTarget.DataContext.MouseOverEntity.Entity.Name,RelativeSource={RelativeSource Self}}" />
</Canvas>

HTH

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号