silverlight - 如何在自定义控件中的数据模板内使用模板绑定(bind)(Silverlight)

标签 silverlight datatemplate templatebinding

我正在尝试创建控件,该控件将采用 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>

但是,这种方法行不通。
使用 TemplateBindingControlPresenter.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/

相关文章:

c# - 在 Windows 应用商店应用程序的 TextBlock 和 PasswordBox 中垂直和水平居中文本

wpf - 如何结合我看似多余的 XAML

wpf - 将焦点设置到项目控件中的第一个文本框

WPF DataTemplate 属性设置在 Content

dependency-properties - 是否可以使用已编译的绑定(bind) (x :Bind) with Relative Source, Templated Parent

silverlight - Silverlight和clientaccesspolicy.xml

silverlight - 在Silverlight中如何发现Color为空?

javascript - 背后的逻辑(启用 Silverlight 调试会禁用 Javascript 调试)?

c# - 如何从 UserControl 实例创建 DataTemplate?

wpf - 如何绑定(bind)到渐变停止 WPF