如何在自定义控件(Silverlight)中的数据模板中使用模板绑定

ste*_*ndo 13 silverlight datatemplate templatebinding

我想创建控制,将采取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);
Run Code Online (Sandbox Code Playgroud)

这是模板:

<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>
Run Code Online (Sandbox Code Playgroud)

但是,这种方法不起作用.
ControlPresenter.ContentTemplate使用TemplateBinding中绑定不起作用.
但是,当我不使用模板绑定并将模板作为静态资源引用时,它会按预期工作.

  • 为什么我不能在datatemplate中的内容展示器中使用模板绑定?
  • 我在这里错过了什么?需要什么特殊标记?
  • 有没有办法实现预期的行为?

提前致谢.

Dun*_*son 19

Silverlight和WPF

你可以通过相对源绑定解决这个问题:

代替:

{TemplateBinding InnerTemplate}
Run Code Online (Sandbox Code Playgroud)

你会用:

{Binding RelativeSource={RelativeSource AncestorType=local:CheckBoxWrapperList}, Path=InnerTemplate}
Run Code Online (Sandbox Code Playgroud)

它有点麻烦,但它的工作原理.

WinRT的

WinRT没有AncestorType.我有一些有用的东西,但它有点令人恐惧.

您可以使用附加属性来存储TemplateBinding值,然后使用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>
Run Code Online (Sandbox Code Playgroud)

我不知道WinRT是否有更好的方法.


Gra*_*ury 11

TemplateBinding只能在ControlTemplate中使用,您可以在DataTemplate中使用它.(DataTemplate在ControlTemplate中的事实并不重要)