6

WPF でカスタム ユーザー コントロールを作成する方法は知っていますが、誰かが ItemTemplate を提供できるようにするにはどうすればよいですか?

他のいくつかの WPF コントロールが混在しているユーザー コントロールがあり、そのうちの 1 つが 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>
4

1 に答える 1

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>
于 2008-11-10T20:19:12.617 に答える