DataContext在Style.Trigger中没有绑定

时间:2012-09-13 01:58:57

标签: wpf xaml mvvm binding datacontext

所以我有一些类似于以下的代码:(原谅任何拼写错误 - 我试图在SO编辑器中简化帖子)

<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')

2 个答案:

答案 0 :(得分:2)

您发布的错误让您觉得自定义控件位于没有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}}"/>

以下是从here复制的示例Freezable对象的代码:

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来避免异常:)

答案 1 :(得分:0)

我通过将UserControl放入资源中,然后用它来更改内容,解决了类似的问题。

例如来自我自己的代码(不同的名称,相同的概念)

update default d use keys "foo"
SET p.children = ARRAY_APPEND(p.children, {
  "id": "20202020",
  "pageURIHash": "99999",
  "children": [],
  "parentId": null,
  "content": "New Stuff"
}) FOR p WITHIN d.children WHEN p.id = "520707440" END