Skip to main content
 首页 » 编程设计

c#之集合上的数据模板

2024年01月01日39yjmyzz

我这里有一个名为 DockGroup 的自定义控件类。我想为 DockGroup 应用样式模板并将数据绑定(bind)应用到 Items 依赖属性(使用自定义数据模板)。

[ContentProperty(@"Items")] 
public class DockGroup : Control 
{ 
    public static readonly DependencyProperty ItemsProperty = 
        DependencyProperty.Register("Items", typeof(ObservableCollection<UIElement>), typeof(DockGroup), new PropertyMetadata(default(ObservableCollection<UIElement>))); 
 
    public ObservableCollection<UIElement> Items 
    { 
        get { return (ObservableCollection<UIElement>)GetValue(ItemsProperty); } 
        set { SetValue(ItemsProperty, value); } 
    } 
 
    public DockGroup() 
    { 
        Items = new ObservableCollection<UIElement>(); 
        DataContext = Items; 
    } 
} 

这是 DockGroup 的样式,还包含 DataTemplate。

<Style TargetType="{x:Type local:DockGroup}"> 
    <Style.Resources> 
        <DataTemplate x:Key="Items" DataType="{x:Type UIElement}"> 
            <Label>I DON'T KNOW WHAT TO PUT IN DATATEMPLATE</Label> 
        </DataTemplate> 
    </Style.Resources> 
    <Setter Property="Template"> 
        <Setter.Value> 
            <ControlTemplate TargetType="{x:Type local:DockGroup}"> 
                <ContentPresenter ContentSource="{Binding}"/> 
            </ControlTemplate> 
        </Setter.Value> 
    </Setter> 
</Style> 

这是我想用来测试的示例 XAML。

<local:DockGroup> 
     <Label Background="#FFF0F077">Hello World!</Label> 
     <Label Background="#FFF0F077">Hello World 2!</Label> 
</local:DockGroup> 

当我运行该项目时,出现一个空白窗口。而且,我似乎无法弄清楚出了什么问题。

请您参考如下方法:

您可以使用 ItemsControl 设置控件的样式以使其工作:

<Style TargetType="{x:Type local:DockGroup}"> 
<Setter Property="Template"> 
  <Setter.Value> 
    <ControlTemplate> 
      <ItemsControl ItemsSource="{Binding Items, RelativeSource={RelativeSource TemplatedParent}}"/> 
    </ControlTemplate> 
  </Setter.Value> 
</Setter>