2

だから私は次のようなコードを持っています:(タイプミスを許してください-私は投稿の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')

4

2 に答える 2

3

DataContext投稿したエラーにより、カスタム コントロールがなどの を持たないオブジェクトにあるように聞こえますDataGridColumn.Header

これを回避するには、探しているバインディングを含むFreezeableオブジェクトを作成し、そのオブジェクトにバインドします。.Resourcesmy: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からコピーしたサンプル オブジェクトのコードを次に示します。

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

于 2012-09-13T16:32:31.577 に答える