2011-01-21 98 views
0

我試圖創建一個複雜的工具提示,其中一個TextBlocks將被綁定到UserControl的屬性中,該工具提示被定義爲資源。在XAML代碼的簡化版本是這樣的:如何訪問資源內的父類

<UserControl x:Class="WpfApplication3.TestPage" 
     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" 
     xmlns:pixellab="clr-namespace:PixelLab.Wpf;assembly=UIControls" 
     xmlns:my="clr-namespace:WpfApplication3" 
     d:DesignHeight="499" d:DesignWidth="409" 
     x:Name="PageInstance" > 
<UserControl.Resources> 
    <Grid x:Key="Tooltip"> 
     <TextBlock Text="{Binding ElementName=PageInstance, Path=PageTest}"/> 
    </Grid> 
</UserControl.Resources> 
<Border Background="Red" ToolTip="{StaticResource Tooltip}" /> 

用戶控件被命名爲PageInstance。裏面顯示的邊框有一個定義爲資源的工具提示。如果我嘗試綁定文本與

<TextBlock Text="{Binding ElementName=PageInstance, Path=PageTest}"/> 

我得到一個綁定錯誤,當我運行的應用程序:

System.Windows.Data錯誤:4:無法爲參照結合找到源「的ElementName = PageInstance '。 BindingExpression:路徑= PageTest;的DataItem = NULL;目標元素是'TextBlock'(Name ='');目標屬性是'文本'(類型'字符串')

我必須做什麼才能成功將文本綁定到PageInstance usercontrol中的PageTest屬性?

感謝您的任何幫助。我還沒有完全弄清楚Bindings是如何工作的。 格雷戈爾

回答

1

Border將繼承UserControlDataContext。因此,修改您的提示這樣...

<Grid x:Key="Tooltip"> 
    <TextBlock Text="{Binding PageTest}"/> 
</Grid> 

...,然後設置你的UserControlDataContext將推動模式與物業PageTest到你Border孩子以後。這避免了需要整體使用FindAncestor

PageInstance.DataContext = model; 
2

在你的綁定使用RelativeSource,這樣的事情:

<TextBlock Text="{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=PageTest}"/> 
+0

+1對賭我在分鐘;) – 2011-01-21 19:44:37