的DataContext在Style.Trigger没有约束力

问题描述:

所以我有类似下面的一些代码:(请原谅我试图在SO编辑一职,以简化任何typos--)的DataContext在Style.Trigger没有约束力

<my:CustomContentControl> 
     <my:CustomContentControl.Style> 
      <Style TargetType="{x:Type my:CustomContentControl}"> 
       <Style.Triggers>       
        <DataTrigger Binding="{Binding Path=CurrentView}" Value="MyCustomView"> 
         <Setter Property="Content"> 
          <Setter.Value> 
           <my:CustomView DataContext="{Binding DataContextForMyCustomView"/> 
          </Setter.Value> 
         </Setter> 
        </DataTrigger> 
       </Style.Triggers> 
      </Style> 
     </m:CustomContentControl.Style> 
</my:CustomContentControl> 

的问题是,每当出现DataTrigger,设置者确实设置Content属性为my:CustomView,但它不是不是绑定DataContext。如果我在触发器之外移动相同的代码,DataContext绑定工作得很好。

任何想法?如果这是某种限制,是否有任何解决方法?

更新:

我收到在输出窗口中出现以下错误:

System.Windows.Data Error: 3 : Cannot find element that provides DataContext. BindingExpression:Path=DataContextForMyCustomView; DataItem=null; target element is 'CustomView' (Name='customView'); target property is 'DataContext' (type 'Object')

+0

在输出窗口中是否有关于此绑定的错误或警告消息? –

+0

@Miklós:很好的建议,谢谢。呃,它让我忘记了输出窗口中出现绑定错误!更新我的问题瓦特/错误现在... – HolySamosa

+0

@HolySamosa你的UserControl是什么?你发布的错误使得它听起来像它没有'DataContext'的对象,比如'DataGridColumn.Header'。此外,如果多个对象应用了该样式,您应该使用'ContentTemplate'而不是'Content'来避免异常。 – Rachel

您发布的错误会使得它听起来像你的自定义控制是一个对象,它不有一个DataContext,如DataGridColumn.Header

要解决这个问题,你可以在你.Resources创建Freezeable对象包含你正在寻找的绑定,然后绑定你的my:CustomView.DataContext到该对象

<my:CustomContentControl.Resources> 
    <local:BindingProxy x:Key="proxy" 
     Data="{Binding DataContextForMyCustomView, ElementName=MyControl}" /> 
</my:CustomContentControl.Resources> 

... 

<my:CustomView DataContext="{Binding Source={StaticResource proxy}}"/> 

下面是复制的样本Freezable对象的代码从here

public class BindingProxy : Freezable 
{ 
    #region Overrides of Freezable 

    protected override Freezable CreateInstanceCore() 
    { 
     return new BindingProxy(); 
    } 

    #endregion 

    public object Data 
    { 
     get { return (object)GetValue(DataProperty); } 
     set { SetValue(DataProperty, value); } 
    } 

    // Using a DependencyProperty as the backing store for Data. 
    // This enables animation, styling, binding, etc... 
    public static readonly DependencyProperty DataProperty = 
     DependencyProperty.Register("Data", typeof(object), 
      typeof(BindingProxy), new UIPropertyMetadata(null)); 
} 

而且,你真的应该使用ContentTemplate而不是Content以避免EXCE如果不止一个对象适用该风格:)