How to bind an element to a property which belongs to the root element of a control?

五迷三道 提交于 2019-12-13 02:36:09

问题


The question may sound a little confusing, but the problem I'm currently facing is this:

<Button x:Class="sandbox.BtnLabel"
        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" 
        x:Name="this">
    <Button.ToolTip>
        <TextBlock Background="Yellow" Text="{Binding ElementName=this, Path=LabelText}"/>
    </Button.ToolTip>
    <TextBlock Background="Yellow" Text="{Binding ElementName=this, Path=LabelText}"/>
</Button>

Only the second binding works, which sets the content of the button. The first one, which I would like to use to set the contents of the tooltip of the button (via the LabelText dependency property) does not work.

Is it possible to make the first binding work? Thanks.


回答1:


Try this:

<Button x:Class="sandbox.BtnLabel"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        x:Name="this">
  <Button.ToolTip>
    <ToolTip DataContext="{Binding Path=PlacementTarget, RelativeSource={RelativeSource Self}}">
      <TextBlock Background="Yellow"
                 Text="{Binding LabelText}" />
    </ToolTip>
  </Button.ToolTip>
  <TextBlock Background="Yellow"
             Text="{Binding ElementName=this,
                            Path=LabelText}" />
</Button>

We add a ToolTip element and assign it's DataContext as it's PlacementTarget which should then reach the TextBlock



来源:https://stackoverflow.com/questions/16924711/how-to-bind-an-element-to-a-property-which-belongs-to-the-root-element-of-a-cont

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!