【问题标题】:Styled textblock binding for tooltip is binding to control template instead工具提示的样式化文本块绑定改为绑定到控件模板
【发布时间】:2011-11-13 21:54:22
【问题描述】:

我正在尝试将文本块的工具提示绑定到文本块文本所绑定的值。

以下作品适用于应用此样式的文本块:

<Style x:Key="GridCell" TargetType="{x:Type TextBlock}">
    <Setter Property="ToolTip" Value="{Binding Converter={StaticResource CellToolTipConverter}}"/>
</Style>

<DataTemplate x:Key="GridCellContentTemplate">
     <TextBlock Style="{StaticResource GridCell}"
                Text="{Binding Converter=..."/>
</DataTemplate>

<xcdg:Column FieldName="FXRate" CellContentTemplate="{GridCellContentTemplate}" />

但出于某种奇怪的原因,当我尝试将此样式作为资源传递给数据网格统计单元格时,

<Style x:Key="{x:Type xcdg:StatCell}" TargetType="{x:Type xcdg:StatCell}">
    <Style.Resources>
        <Style x:Key="{x:Type TextBlock}" TargetType="{x:Type TextBlock}">
             <Setter Property="ToolTip" Value="{Binding Converter={StaticResource CellToolTipConverter}}"/>
        </Style>
    </Style.Resources>
</Style>

<xcdg:StatCell FieldName="Limit">
      <TextBlock Text="{Binding Source={StaticResource Layers}, Path=StatLimit, Converter=..." />
</xcdg:StatCell>

如您所见,工具提示被绑定到某个 DataTemplate,而不是文本框文本所绑定的任何内容。不过据我所知,这两者没有区别,实际上后者似乎更直接。

谁能弄清楚为什么第二个工具提示绑定不像第一个那样工作?


注意我可以确定绑定正在进入单元格中的文本框,因为如果我将绑定更改为:

<Style x:Key="{x:Type xcdg:StatCell}" TargetType="{x:Type xcdg:StatCell}">
    <Style.Resources>
        <Style x:Key="{x:Type TextBlock}" TargetType="{x:Type TextBlock}">
             <Setter Property="ToolTip" Value="{Binding Path=Text, RelativeSource={x:Static RelativeSource.Self}, Converter={StaticResource CellToolTipConverter}}"/>
        </Style>
    </Style.Resources>
</Style>

我明白了:

当然,我不想要 textblock 文本属性,我想要 textblock 绑定到的原始值。

【问题讨论】:

  • 为什么不简单地将适用的样式应用于文本框?又名&lt;TextBlock Style="{StaticResource GridCell}"/&gt;
  • @Tejs - 效果相同。将 statcell 更改为类似于 &lt;xcdg:StatCell FieldName="Limit"&gt;&lt;TextBlock Style="{StaticResource GridCell}"&gt; 会导致工具提示显示“System.Windows.DataTemplate”
  • 我刚刚注意到这一点,您的键名应该是参考吗?我认为x:Key 必须是一个简单的字符串(例如:x:Key="{x:Type TextBlock}" 这对我来说看起来很奇怪。但它可能什么都不是(它只是那个字符串值作为键)。
  • 将 x:Key 设置为一个类型会使该样式成为该类型所有元素的默认样式。这就像你要指定一个目标类型而根本没有 x:key - 我只是更喜欢明确。

标签: c# wpf xaml binding


【解决方案1】:

这样做的原因是文本绑定正在查看工具提示所附加到的对象的数据上下文。恰好 xcdg:StatCell 出于自己的目的劫持了数据上下文,因此任何子视觉元素都无法访问绑定到的原始属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-15
    • 1970-01-01
    • 2018-06-13
    • 1970-01-01
    相关资源
    最近更新 更多