gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 14:45:07 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com