【问题标题】:ToolTip is null. How do I access it?工具提示为空。我如何访问它?
【发布时间】:2011-12-27 15:40:34
【问题描述】:

在我的自定义控件中,我想根据选项以编程方式启用或禁用工具提示。这是我在模板中定义的图标的方式:

<Image x:Name="PART_IconImage" Stretch="None" VerticalAlignment="Top" HorizontalAlignment="Center" Source="{TemplateBinding Icon}" 
                                   ToolTipService.ToolTip="{TemplateBinding Caption}" />

我正在使用此代码访问工具提示并启用/禁用它:

// Enable tooltip when caption not shown
            if (this.IconImage != null)
            {
                var toolTip = ToolTipService.GetToolTip(this.IconImage) as ToolTip;

                if (toolTip != null)
                    toolTip.IsEnabled = this.CaptionVisibility.HasValue
                                        ? (this.CaptionVisibility.Value == Visibility.Collapsed)
                                        : (this.ParentToolbar.CaptionsVisibility == Visibility.Collapsed);
            }

GetToolTip 返回 null。知道为什么吗?

附:我在这里遵循这个建议:How to programmatically access ToolTipService of a Silverlight FrameworkElement? 但这对我不起作用。

【问题讨论】:

    标签: c# silverlight xaml


    【解决方案1】:

    您确定ToolTipService.GetToolTip 返回的是空值,而不是返回ToolTip 以外的值吗?

    我对与您的代码类似的代码做了一个快速实验,发现ToolTipService.GetToolTip 返回了一个字符串。我当然将ToolTipService.ToolTip 绑定到一个字符串依赖属性。我怀疑你也从GetToolTip 得到了一个字符串,但是你在调用这个方法之后添加的as ToolTip 会取消这个字符串。

    以编程方式禁用工具提示的一种方法是将其绑定到视图模型上的属性,如果应该显示工具提示,则该属性包含工具提示文本;如果不应该显示工具提示,则将其绑定到 null。

    或者,您可以使用ToolTip,而不是字符串,作为控件的工具提示。这样,您应该能够访问 ToolTip 对象并在上面的代码中启用/禁用它:

    <Image x:Name="PART_IconImage" Stretch="None" VerticalAlignment="Top" HorizontalAlignment="Center" Source="{TemplateBinding Icon}">
        <ToolTipService.ToolTip>
            <ToolTip>
                <TextBlock Text="{TemplateBinding Caption}" />
            </ToolTip>
        </ToolTipService.ToolTip>
    </Image> 
    

    【讨论】:

    • 您可能更正了它返回的字符串。我没有检查那个。我不想绑定,因为它不是我控制的公共财产。我已经通过完全删除 XAML 并在需要时编写代码来执行 ToolTipService.SetToolTip 解决了这个问题。我会标记你的答案,因为它会按照你的方式工作,而且我已经有了答案
    【解决方案2】:

    为什么不简单地将下面的属性与 bool 属性绑定?

    ToolTipService.IsEnabled 
    

    然后,只要您想禁用/启用,只需更改绑定的属性

    Image ToolTipService.IsEnabled="{Binding Path=SomeProperty}">

    也可以看看How do you disable tooltips in code at runtime

    【讨论】:

    • 然后看看我提到的链接可能对你有帮助
    • 他说得有道理,现在你愿意使用绑定但不使用 MVVM。这很骇人听闻。
    • 我删除了所有以前的 cmets。 Silverlight 不会将 IsEnabled 公开为依赖属性。即使是这样 - 我不想在我的控件中公开这些属性
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-28
    • 2013-03-07
    • 2015-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-20
    相关资源
    最近更新 更多