如何在自定义控件中的数据模板中使用模板绑定 (Silverlight) [英] How to use template binding inside data template in custom control (Silverlight)
问题描述
我正在尝试创建控件,该控件将采用 ItemsSource
和 InnerTemplate
,并将显示包裹在 CheckBox
es 中的所有项目.
I am trying to create control which will take ItemsSource
and InnerTemplate
and will show all the items wrapped in CheckBox
es.
控件有 2 个依赖属性:
The control has 2 dependency properties:
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
中绑定不起作用.
但是,当我不使用模板绑定并将模板作为静态资源引用时,它会按预期工作.
However, this approach does not work.
Binding in the ControlPresenter.ContentTemplate
using TemplateBinding
does not work.
However, when I don't use template binding and reference the template as static resource, then it works as expected.
- 为什么我不能在数据模板的内容展示器中使用模板绑定?
- 我在这里遗漏了什么?需要什么特殊的标记吗?
- 有没有办法实现预期的行为?
提前致谢.
推荐答案
TemplateBinding 只能在 ControlTemplate 中使用,您是在 DataTemplate 中使用它.(DataTemplate 在 ControlTemplate 内的事实无关紧要)
TemplateBinding can only be used within a ControlTemplate, you're using it within a DataTemplate. (The fact that the DataTemplate is within a ControlTemplate doesn't matter)
这篇关于如何在自定义控件中的数据模板中使用模板绑定 (Silverlight)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!