C# 带有项/数据模板的WPF自定义控件
我知道如何在WPF中创建自定义用户控件,但我如何才能使其成为可以提供ItemTemplate的控件 我有一个用户控件,它是其他几个WPF控件的混合体,其中一个是ListBox。我想让控件的用户指定列表框的内容,但我不确定如何传递该信息 编辑:接受的答案与以下更正一起工作:C# 带有项/数据模板的WPF自定义控件,c#,wpf,wpf-controls,user-controls,C#,Wpf,Wpf Controls,User Controls,我知道如何在WPF中创建自定义用户控件,但我如何才能使其成为可以提供ItemTemplate的控件 我有一个用户控件,它是其他几个WPF控件的混合体,其中一个是ListBox。我想让控件的用户指定列表框的内容,但我不确定如何传递该信息 编辑:接受的答案与以下更正一起工作: <UserControl x:Class="WpfApplication6.MyControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/prese
<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>
这还没有我想象的那么糟糕。在我能够验证它是否有效后,我会接受。好的,我已经开始工作了,但我需要做一个更正。我将在我的原始问题中发布它。哦,对了,我忘记了ItemTemplate绑定的属性。我也会修正我的答案。