2

我在这里有一个名为 DockGroup 的自定义控件类。我想为 DockGroup 应用样式模板并将数据绑定到 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>

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

4

1 回答 1

0

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

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

于 2013-03-30T09:07:27.980 回答