簡體   English   中英

具有項目/數據模板的WPF自定義控件

[英]WPF Custom Control with Item/Data Templates

我知道如何在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>

您將需要向您的控件添加一個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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM