如何在自定义控件(Silverlight)中的数据模板内使用模板绑定
我正在尝试创建控件,该控件将获取如何在自定义控件(Silverlight)中的数据模板内使用模板绑定,silverlight,datatemplate,templatebinding,Silverlight,Datatemplate,Templatebinding,我正在尝试创建控件,该控件将获取ItemsSource和InnerTemplate,并将显示包装在复选框中的所有项目 控件有2个依赖项属性: public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.Register("ItemsSource", typeof(IEnumerable), typeof(CheckBoxWrapperList), null); public static r
ItemsSource
和InnerTemplate
,并将显示包装在复选框中的所有项目
控件有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内部使用模板绑定李>
- 我错过了什么?需要特殊标记吗李>
- 有没有达到预期行为的方法
提前感谢。TemplateBinding只能在ControlTemplate中使用,您正在DataTemplate中使用它。(DataTemplate在ControlTemplate中这一事实并不重要)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>
我不知道是否有更好的办法来解决温特的问题。你找到了吗?我也有同样的问题。@P.W.呃,太麻烦了。嗯。我已经想出了一些技术上可行的方法,补充了答案。