2011-01-21 71 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