You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF ListBoxItem ToolTip从Collapsed切换为Visible时显示异常

解决方案

你的问题核心是WPF默认会复用ToolTip实例,导致悬停空提示的Item后,ToolTip的状态残留到后续Item上。以下是两种简便修复方式:

方法一:给每个ListBoxItem分配独立的ToolTip实例

修改ListBoxItem的容器样式,直接在ToolTip属性中声明实例并设置x:Shared="False",确保每个Item拥有专属的ToolTip,避免复用导致的状态残留:

<ListBox.ItemContainerStyle>
    <Style TargetType="ListBoxItem">
        <Setter Property="ToolTip">
            <Setter.Value>
                <ToolTip x:Shared="False"
                         Content="{Binding Converter={StaticResource ItemValueToTooltipConverter}}"
                         Visibility="{Binding Converter={StaticResource ItemValueToTooltipVisibilityConverter}}"/>
            </Setter.Value>
        </Setter>
    </Style>
</ListBox.ItemContainerStyle>

之前的类型转换错误大概率是因为把x:Shared="False"放在了Style上,现在直接作用于ToolTip实例即可解决。如果需要保留第三方ToolTip样式,直接在ToolTip实例上引用即可:

<ToolTip x:Shared="False" Style="{StaticResource ThirdPartyToolTipStyle}" .../>

方法二:优化Converter逻辑,避免ToolTip实例缓存

修改ItemValueToTooltipVisibilityConverter,当提示文本为空时,主动清空ToolTip的Content,避免空值缓存:

public class ItemValueToTooltipVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        string tooltipText = value?.ToString();
        if (string.IsNullOrEmpty(tooltipText))
        {
            var tooltip = parameter as ToolTip;
            tooltip?.SetValue(ToolTip.ContentProperty, null);
            return Visibility.Collapsed;
        }
        return Visibility.Visible;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

然后在XAML中给Converter传递ToolTip实例作为参数:

<ToolTip Visibility="{Binding Converter={StaticResource ItemValueToTooltipVisibilityConverter}, ConverterParameter={RelativeSource Self}}"
         Content="{Binding Converter={StaticResource ItemValueToTooltipConverter}}"/>

这种方法无需修改资源共享设置,通过主动清空Content避免残留。

额外检查点

确认ItemValueToTooltipConverter的逻辑,确保针对Item1确实返回空字符串,无其他隐性返回值干扰。

内容的提问来源于stack exchange,提问作者laurencijus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 22:05:16