2015-05-04 42 views
0

我想访问资源中的父DataContext以在绑定中使用它。下面是示例:绑定到父DataContext的资源

<Window x:Class="WpfApplication44.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:l="clr-namespace:WpfApplication44" 
    x:Name="MyWindows" 
    Title="MainWindow" 
    Width="525" 
    Height="350" 
    DataContext="{Binding RelativeSource={RelativeSource Self}}"> 

<Window.Resources> 
    <l:SomeResource x:Key="SomeResource"> 
     <l:SomeResource.Context> 
      <!-- 
       DataContext is set to windows object. 
       I want to bind to window`s title property 
      --> 
      <Binding Path="Title" /> 
     </l:SomeResource.Context> 
    </l:SomeResource> 
</Window.Resources> 

<StackPanel> 
    <Label> 
     <StaticResource ResourceKey="SomeResource" /> 
    </Label> 

    <!-- UPD --> 
    <TextBlock Text="{Binding Source={StaticResource SomeResource}, Path=Context}" /> 
</StackPanel> 

,但我得到:

System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=Title; DataItem=null; target element is 'SomeResource' (HashCode=25557385); target property is 'Context' (type 'Object')

SomeResource是自DependencyObject派生,并包含类型的对象只有一个依赖属性上下文。

它看起来像资源无权访问父级的DataContext属性,并且如果资源的类型为FrameworkElement,则不会设置事件。我试图在绑定中使用ElementName,RelativeSource,但没有运气。

我需要的是将父级的DataContext设置为资源。我使用MVVM,因此任何MVVM解决方案都是可取的。

UPD 链接到项目here

+0

它的工作对我罚款。请提供'Window'和'SomeResource'的代码隐藏功能! – sac1

+0

嗨,@ sac1,这里是链接到完整的项目:http://1drv.ms/1brwkVZ。你有没有使用我的代码?谢谢 – aderesh

回答

0

哦,它看起来像一个DataProxy比修改SomeResourceFreezable这样的:

public class SomeResource : Freezable 
{ 
    protected override Freezable CreateInstanceCore() 
    { 
     return new SomeResource(); 
    } 

    public static readonly DependencyProperty ContextProperty = DependencyProperty.Register("Context", typeof(object), typeof(SomeResource), new PropertyMetadata(default(object))); 

    public object Context 
    { 
     get { return (object)GetValue(ContextProperty); } 
     set { SetValue(ContextProperty, value); } 
    } 
} 
+0

谢谢,它的工作原理。在发布这个问题之前我曾尝试过,但也许我错过了一些东西。 – aderesh