2008-11-10 68 views
4

我知道如何在WPF中創建一個自定義用戶控件,但我怎樣才能讓它有人可以提供一個ItemTemplate?WPF與項目/數據模板的自定義控件

我有一個用戶控件是其他幾個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> 

回答

14

你會想對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); } 
    } 
} 

這是用戶控件的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> 
+0

,因爲我是做出來的人,這不是幾乎一樣糟糕。在我能夠驗證它是否有效後我會接受。 – 2008-11-10 22:00:38