カスタムコントロールでテンプレートバインディングテンプレート内のテンプレートを使用する方法(Silverlight)

StackOverflow https://stackoverflow.com/questions/4635216

質問

私は取るコントロールを作成しようとしています ItemsSourceInnerTemplate 包まれたすべてのアイテムが表示されます CheckBoxes。

コントロールには2つの依存関係プロパティがあります。

public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.Register("ItemsSource", typeof(IEnumerable), typeof(CheckBoxWrapperList), null);
public static readonly DependencyProperty InnerTemplateProperty = DependencyProperty.Register("InnerTemplate", typeof(DataTemplate), typeof(CheckBoxWrapperList), null);

そして、これがテンプレートです:

<ControlTemplate TargetType="local:CheckBoxWrapperList">
    <Grid>
        <Grid.Resources>
            <DataTemplate x:Key="wrapper">
                <CheckBox>
                    <ContentPresenter ContentTemplate="{TemplateBinding InnerTemplate}" Content="{Binding}" />
                </CheckBox>
            </DataTemplate>
        </Grid.Resources>
        <ItemsControl ItemTemplate="{StaticResource wrapper}" ItemsSource="{TemplateBinding ItemsSource}" />
    </Grid>
</ControlTemplate>

ただし、このアプローチは機能しません。
のバインディング ControlPresenter.ContentTemplate 使用 TemplateBinding 動作しません。
ただし、テンプレートバインディングを使用していない場合、テンプレートを静的リソースとして参照すると、予想どおりに機能します。

  • DataTemplateのコンテンツプレゼンター内でテンプレートバインディングを使用できないのはなぜですか?
  • ここに何が欠けていますか?特別なマークアップが必要ですか?
  • 予想される動作を達成する方法はありますか?

前もって感謝します。

役に立ちましたか?

解決

テンプレートバインディングは、ControlTemplate内でのみ使用できます。データセット内で使用しています。 (DataTemplateがControlTemplate内にあるという事実は問題ではありません)

他のヒント

シルバーライトとWPF

相対ソースのバインディングでこれを回避できます。

それ以外の:

{TemplateBinding InnerTemplate}

あなたが使用するでしょう:

{Binding RelativeSource={RelativeSource AncestorType=local:CheckBoxWrapperList}, Path=InnerTemplate}

少し厄介ですが、機能します。

winrt

WinrtにはAncestortypeがありません。私が持っている なにか それはうまくいきますが、それはちょっと恐ろしいです。

添付のプロパティを使用してテンプレートバインディング値を保存し、elementNameを使用してアクセスできます...

<ControlTemplate TargetType="local:CheckBoxWrapperList">
    <Grid x:Name="TemplateGrid" magic:Magic.MagicAttachedProperty="{TemplateBinding InnerTemplate}">
        <Grid.Resources>
            <DataTemplate x:Key="wrapper">
                <CheckBox>
                    <ContentPresenter ContentTemplate="{Binding ElementName=TemplateGrid, Path=(magic:Magic.MagicAttachedProperty)}" Content="{Binding}" />
                </CheckBox>
            </DataTemplate>
        </Grid.Resources>
        <ItemsControl ItemTemplate="{StaticResource wrapper}" ItemsSource="{TemplateBinding ItemsSource}" />
    </Grid>
</ControlTemplate>

Winrtにもっと良い方法があるかどうかはわかりません。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top