14

我正在尝试创建控件,该控件将显示ItemsSource并显示包含在esInnerTemplate中的所有项目。CheckBox

该控件有 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.ContentTemplateTemplateBinding

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

提前致谢。

4

2 回答 2

21

Silverlight 和 WPF

您可以通过相对源绑定来解决此问题:

代替:

{TemplateBinding InnerTemplate}

你会使用:

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

它有点混乱,但它有效。

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>

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

于 2012-03-20T02:08:12.920 回答
13

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

于 2011-07-19T16:05:30.773 回答