【问题标题】:Unable to set the parent datacontext for datatemplate tooltip无法为数据模板工具提示设置父数据上下文
【发布时间】:2019-08-04 00:49:50
【问题描述】:

无法为数据模板工具提示设置父数据上下文。

下面是 xaml 代码。只需一次组合框并在组合框数据模板中添加文本框。

Xaml

<UserControl x:Class="WpfApplication1.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             Name="UC"
             d:DesignHeight="50" d:DesignWidth="200">
    <Grid>
        <ComboBox Width="200" Height="50" ItemsSource="{Binding Coll}">
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Length}">
                        <TextBlock.ToolTip>
                            <ToolTip Content="{Binding Path=DataContext.ToolTipValue, 
                                                       RelativeSource={RelativeSource FindAncestor, 
                                                       AncestorType={x:Type UserControl}}}"/>
                        </TextBlock.ToolTip>
                    </TextBlock>
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>
    </Grid>
</UserControl>

视图模型

    private List<string> _coll;

    public List<string> Coll
    {
        get { return _coll; }
        set { _coll = value; OnPropertyChanged(); }
    }

    private string _ToolTipValue;

    public string ToolTipValue
    {
        get { return _ToolTipValue; }
        set { _ToolTipValue = value; OnPropertyChanged(); }
    }

    public ViewModel()
    {
        _coll = new List<string>(){ "1", "2", "3"};
        _ToolTipValue = "Demo";
    }

你能帮我解释一下为什么没有设置 DataContext。

是绑定问题吗?

【问题讨论】:

  • 你需要调用ToolTipValue = "something来触发它的setter和OnPropertyChanged,你不应该和私有属性交互。
  • 您能否详细说明一下,我在构造函数中将值设置为私有字段。组合框 itemsource 工作正常
  • 同意,它有效。想象一下您稍后更改值。私有属性不会更新更改的属性!
  • 你能多加一点xaml吗?至少您所指的用户控件
  • 我只是在尝试示例演示,但无法设置工具提示文本

标签: c# wpf xaml


【解决方案1】:

如果你不需要任何特殊的东西尽量不要嵌套工具提示:

<TextBlock ToolTip="{Binding DataContext.ToolTipValue, 
                     RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}"
           Text="{Binding Length}"/>

【讨论】:

  • 谢谢 知道了,但我可以知道为什么它在我的代码中不起作用吗?
  • @superuser 老实说..我不知道..:D
猜你喜欢
  • 2015-08-11
  • 2013-04-16
  • 2016-06-05
  • 1970-01-01
  • 2016-08-10
  • 1970-01-01
  • 1970-01-01
  • 2018-04-04
  • 1970-01-01
相关资源
最近更新 更多