我正在尝试创建控件,该控件将采用 ItemsSource
和 InnerTemplate
并将显示包含在 CheckBox
es 中的所有项目。
该控件有 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
中进行绑定(bind)不起作用。
但是,当我不使用模板绑定(bind)并将模板引用为静态资源时,它会按预期工作。
- 为什么我不能在数据模板的内容呈现器中使用模板绑定(bind)?
- 我在这里缺少什么?需要什么特殊标记吗?
- 有办法实现预期的行为吗?
提前致谢。
最佳答案
Silverlight 和 WPF
您可以通过相对源绑定(bind)来解决这个问题:
而不是:
{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是否有更好的方法。
关于silverlight - 如何在自定义控件中的数据模板内使用模板绑定(bind)(Silverlight),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4635216/