如何访问资源中的父类

时间:2011-01-21 19:32:45

标签: wpf data-binding binding resources

我正在尝试创建一个复杂的工具提示,其中一个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}" />

UserControl被命名为PageInstance。内部显示的边框有一个工具提示,定义为资源。如果我尝试用

绑定文本
<TextBlock Text="{Binding ElementName=PageInstance, Path=PageTest}"/>

运行应用时遇到绑定错误:

System.Windows.Data错误:4:找不到具有引用'ElementName = PageInstance'的绑定源。 BindingExpression:路径= PageTest;的DataItem = NULL; target元素是'TextBlock'(Name =''); target属性是'Text'(类型'String')

如何成功将文本绑定到PageInstance usercontrol中的PageTest属性,我该怎么办?

感谢您的帮助。我还没有完全弄清楚Bindings是如何工作的。 格里

2 个答案:

答案 0 :(得分:2)

在绑定中使用RelativeSource,如下所示:

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

答案 1 :(得分:1)

Border将继承DataContext的{​​{1}}。因此,修改工具提示......

UserControl

...然后在<Grid x:Key="Tooltip"> <TextBlock Text="{Binding PageTest}"/> </Grid> 上设置DataContext会将包含属性UserControl的模型推送到您的PageTest及其后的子项。这样就无需完全使用Border

FindAncestor