带项目/数据模板的WPF自定义控件

时间:2008-11-10 19:07:56

标签: c# wpf wpf-controls user-controls

我知道如何在WPF中创建自定义用户控件但是如何才能创建它以便有人可以提供ItemTemplate?

我有一个用户控件,它是几个其他WPF控件的混合,其中一个是ListBox。我想让控件的用户指定列表框的内容,但我不确定如何传递该信息。

编辑:接受的答案适用于以下更正:

<UserControl x:Class="WpfApplication6.MyControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:src="clr-namespace:WpfApplication6">
    <ListBox ItemTemplate="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type src:MyControl}}, Path=ItemsSource}" />
</UserControl>

1 个答案:

答案 0 :(得分:15)

您需要向控件添加DependencyProperty。如果从UserControl或Control派生,则xaml看起来会略有不同。

public partial class MyControl : UserControl
{
    public MyControl()
    {
        InitializeComponent();
    }

    public static readonly DependencyProperty ItemTemplateProperty =
        DependencyProperty.Register("ItemTemplate", typeof(DataTemplate), typeof(MyControl), new UIPropertyMetadata(null));
    public DataTemplate ItemTemplate
    {
        get { return (DataTemplate) GetValue(ItemTemplateProperty); }
        set { SetValue(ItemTemplateProperty, value); }
    }
}

这是用于UserControl的xaml。

<UserControl x:Class="WpfApplication6.MyControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:src="clr-namespace:WpfApplication6">
    <ListBox ItemTemplate="{Binding ItemTemplate, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type src:MyControl}}}" />
</UserControl>

以下是控件的xaml:

<Style TargetType="{x:Type src:MyControl}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type src:MyControl}">
                <Border Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}">

                    <ListBox ItemTemplate="{TemplateBinding ItemTemplate}" />
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>