我在这里有一个名为 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>
当我运行该项目时,我得到一个空白窗口。而且,我似乎无法弄清楚出了什么问题。