2013-06-04 118 views
1

問題可能聽起來有點混亂,但我目前所面臨的問題是這樣的:如何將元素綁定到屬於控件的根元素的屬性?

<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> 

只有第二綁定工作,設定按鈕的內容。第一個,我想用來設置按鈕的工具提示內容(通過LabelText依賴屬性)不起作用。

是否有可能使第一個綁定工作? 謝謝。

+0

看一看[這](http://stackoverflow.com /一個/1466627分之2439911)。 –

+0

感謝您的參考,但它不起作用。 我得到的錯誤是: System.Windows.Data錯誤:4:找不到與參考'ElementName = this'綁定的源。 BindingExpression:路徑= LabelText的;的DataItem = NULL;目標元素是'TextBlock'(Name ='');目標屬性是'文本'(類型'字符串') – bsguedes

+0

試一試.... Text = {Binding RelativeSource = {RelativeSource FindAncestor,AncestorType = {x:Type Button}},Path = LabelText} – jure

回答

4

試試這個:

<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> 

我們添加一個ToolTip元素,併爲其分配的DataContext,因爲它是PlacementTarget然後應達到TextBlock

+0

太棒了!那就像我期待的一樣!我不知道'PlacementTarget'是如何工作的。很多!(不幸的是我不能投票,因爲我沒有足夠的聲譽) – bsguedes

+0

歡迎您:)不要擔心abt upvote – Viv

相關問題