2008-11-10 4 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); } 
    } 
} 

다음은 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> 
+0

. 내가 작동하는지 확인할 수있게되면 받아 들일 것입니다. –

+0

좋아, 나는이 일을하고 있지만 내가해야 할 한가지 수정이 있었다. 원래의 질문에 게시 할 것입니다. –

+1

아, 바로 ItemTemplate 바인딩에 대한 속성을 잊어 버렸습니다. 내 대답도 고쳐 줄거야. –