【问题标题】:How to use template binding inside data template in custom control (Silverlight)如何在自定义控件中的数据模板中使用模板绑定(Silverlight)
【发布时间】:2011-06-05 20:00:09
【问题描述】:

我正在尝试创建将采用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>

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

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

提前致谢。

【问题讨论】:

  • 你明白了吗?我也有同样的问题。

标签: silverlight datatemplate templatebinding


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    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.呃,那很乱。嗯。我已经制定了一些技术上可行的方法,并添加到答案中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-06
    • 1970-01-01
    • 2011-01-16
    相关资源
    最近更新 更多