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

WPF ToolTip绑定异常:类型转换失败及显示控制问题

问题:ToolTip绑定后台属性时的显示控制与初始化错误

此前该问题被标记为另一问题的重复项,但二者核心问题不同:另一问题是将ToolTip绑定到其他元素的值,而本文场景是绑定到后台代码声明的公共属性,无需使用PlacementTarget;此外,本文还涉及ToolTip初始化阶段的UnsetValue问题,这也是另一问题未覆盖的内容。已修改标题以匹配实际问题,希望能帮助到同样在这类需求上耗费时间的开发者。

最初遇到无法将MS.Internal.NamedObject转换为[x]的错误,按理解是绑定找不到指定属性,但用两个TextBlock调试时,绑定能正常工作。尝试了多种方法仍未解决问题。

需求

当ToolTip文本为空或通过布尔值ShowToolTip设置为“隐藏”时,不显示该ToolTip。

相关代码

XAML代码

<UserControl x:Class="TidyDesk.UserControls.BoxButton"
             [...]
             xmlns:local="clr-namespace:TidyDesk.UserControls"
             xmlns:conv="clr-namespace:TidyDesk.Converters"
             mc:Ignorable="d" 
             
             Width="{Binding BtnSize}"
             Height="{Binding RelativeSource={RelativeSource Self}, Path=Width}"
             Name="ThisUserControl"
             d:DesignHeight="100" d:DesignWidth="100">

    <UserControl.Resources>
        [...]
        <conv:ToolTipVisibilityMultiConverter x:Key="TTVisConv"/>
    </UserControl.Resources>

    <StackPanel>
        <TextBlock Text="{Binding ShowToolTip}"/>
        <TextBlock Text="{Binding ToolTipText}"/>
        <Image Name="img" Stretch="Fill"
               Source="{Binding ImgPath}"
               Width="{Binding ImgSize}"
               Height="{Binding RelativeSource={RelativeSource Self}, Path=Width}"
           >

        <Image.ToolTip>
            <ToolTip Content="{Binding ToolTipText}" ToolTipService.InitialShowDelay="10">
                <ToolTip.Visibility>
                    <MultiBinding Converter="{StaticResource TTVisConv}">
                        <Binding Path="DataContext.ShowToolTip" ElementName="ThisUserControl"/>
                        <Binding Path="DataContext.ToolTipText" ElementName="ThisUserControl" />
                    </MultiBinding>
                </ToolTip.Visibility>
            </ToolTip>
        </Image.ToolTip>
        [...]
        </Image>
        [...]
    </StackPanel>
</UserControl>

UserControl后台代码

namespace TidyDesk.UserControls
{
    public partial class BoxButton : UserControl
    {
        public BoxButton()
        {
            InitializeComponent();
            DataContext = this;
            [...]
        }

        [...]

        public string ToolTipText { get; set; } = "";
        public bool ShowToolTip { get; set; } = true;
    }
}

转换器代码

namespace TidyDesk.Converters
{
    public class ToolTipVisibilityMultiConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            if (!(bool)values[0] || String.IsNullOrEmpty((string)values[1]))
                return Visibility.Collapsed;
            else
                return Visibility.Visible;
        }

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

尝试过的绑定方式

  • <Binding Path="DataContext.ShowToolTip" ElementName="ThisUserControl"/>
  • <Binding Path="ShowToolTip" ElementName="ThisUserControl"/>
  • <Binding Path="ShowToolTip" RelativeSource="{RelativeSource FindAncestor, AncestorType=local:BoxButton}"/>
  • <Binding Path="ShowToolTip" RelativeSource="{RelativeSource FindAncestor, AncestorType=UserControl}"/>
  • <Binding Path="DataContext.ShowToolTip" RelativeSource="{RelativeSource FindAncestor, AncestorType=Image}"/>

除最后一种仅能在ToolTip内尝试外,其他绑定方式在TextBlock中都能正常工作,但在ToolTip中绑定始终触发以下错误:

System.InvalidCastException: 'Unable to cast object of type 'MS.Internal.NamedObject' to type 'System.Boolean'.'

无效的解决尝试

发现错误可能源于ToolTip未初始化时返回UnsetValue,尝试过滤该值:

if (values[0] != DependencyProperty.UnsetValue && values[1] != DependencyProperty.UnsetValue)
    return Visibility.Collapsed;

但这样会导致ToolTip始终处于Collapsed状态,且绑定仍提示“找不到源”。

疑问

问题出在哪里?是不是忽略了什么明显的点?


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 08:28:13