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

15

我正在尝试创建一个控件,该控件将使用ItemsSourceInnerTemplate,并将显示所有包含在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>
然而,这种方法不起作用。
使用TemplateBinding将绑定到ControlPresenter.ContentTemplate中的内容模板不起作用。
但是,当我不使用模板绑定并将模板作为静态资源引用时,它按预期工作。

  • 为什么不能在datatemplate中的content presenter中使用模板绑定?
  • 我漏了什么吗?需要任何特殊标记吗?
  • 有没有办法实现预期的行为?

谢谢提前。


你解决了吗?我也遇到了同样的问题。 - Alireza
2个回答

23

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方式。


@P.W. 嗯,有点乱。我已经想出了一个技术上可行的解决方案,正在添加到答案中。 - Duncan Matheson

14

TemplateBinding只能在ControlTemplate中使用,您正在DataTemplate中使用它。(DataTemplate位于ControlTemplate内部并不重要)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接