ste*_*ndo 13 silverlight datatemplate templatebinding
我想创建控制,将采取ItemsSource和InnerTemplate并会显示包裹在所有项目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中绑定不起作用.
但是,当我不使用模板绑定并将模板作为静态资源引用时,它会按预期工作.
提前致谢.
Dun*_*son 19
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是否有更好的方法.
Gra*_*ury 11
TemplateBinding只能在ControlTemplate中使用,您可以在DataTemplate中使用它.(DataTemplate在ControlTemplate中的事实并不重要)