我正在尝试创建控制的控制 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中使用它。 (DataTemplate在ControlTemplate中的事实无关紧要)

其他提示

Silverlight和WPF

您可以使用相对源绑定来解决此问题:

代替:

{TemplateBinding InnerTemplate}

您将使用:

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

这有点混乱,但有效。

Winrt

Winrt没有祖先。我有 某物 这有效,但这很恐怖。

您可以使用附件属性存储模板键入值,然后使用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