2012-06-14 2 views
1

다음 사용자 정의 컨트롤에 대한 컨트롤 템플릿을 정의했습니다.ControlTemplate을 수정하여 항목을 내 사용자 지정 컨트롤에 직접 추가하는 방법

<ControlTemplate TargetType="{x:Type local:CustomControl}"> 
    <Grid x:Name="MainGrid"> 
     <Grid.ColumnDefinitions> 
      <ColumnDefinition Width="*" /> 
      <ColumnDefinition Width="Auto" /> 
     </Grid.ColumnDefinitions> 
     <local:CustomPanel x:Name="MyCustomPanel" Grid.Column="0" /> 
     <ScrollBar Grid.Column="1" Width="20" /> 
    </Grid> 
</ControlTemplate> 

여기서 CustomPanel은 Panel 클래스 형식을 가져옵니다. 지금은 내가 XAML에서 직접 내 사용자 지정 컨트롤에 항목을 추가 할 수있는 일이

<local:CustomControl x:Name="CControl" Grid.Row="1"> 
    <Button/> 
    <Button/> 
    <Button/> 
</local:CustomControl> 

처럼 직접 내 CustomControl에 항목을 추가 할 수 없습니다?

+0

사용자 정의 패널이 설정되어 있지 않은 것 콘텐츠 속성을 가지고 있습니까? – Andy

+0

@GoldkinG : 답변을 업데이트했습니다. –

답변

1

다음은 사용자가 원하는대로 콘텐츠를 직접 추가 할 수있는 샘플 컨트롤입니다. 관심의

선이 여기에 MyCustomControl 클래스의 상단에있는 속성이며,이는 직접 추가 내용에 배치해야합니다의 property XAML 편집기를 알려줍니다. XAML 코드에서

가 중요한 라인의 ItemsControl에있다 Items 속성에 바인딩되면 실제로 각 항목이 표시됩니다.

C#을

[ContentProperty("Items")] 
public class MyCustomControl : Control 
{ 
    public ObservableCollection<Object> Items 
    { 
     get { return (ObservableCollection<Object>)GetValue(ItemsProperty); } 
     set { SetValue(ItemsProperty, value); } 
    } 

    public static readonly DependencyProperty ItemsProperty = 
     DependencyProperty.Register("Items", typeof(ObservableCollection<Object>), typeof(MyCustomControl), new UIPropertyMetadata(new ObservableCollection<object>()));   
} 

XAML

<Style TargetType="{x:Type local:MyCustomControl}"> 
    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="{x:Type local:MyCustomControl}"> 
       <ItemsControl ItemsSource="{TemplateBinding Items}" /> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 

<local:MyCustomControl> 
    <Button /> 
    <Button /> 
</local:MyCustomControl> 
+0

C# 속성이 약간 자세한 정보를 표시하는 경우 코드 스 니피트이므로 propdp를 입력하고 Tab 키를 두 번 누릅니다. – Andy

3

CustomControl에서 [ContentProperty(PropertyName)]을 사용하십시오.

및 : 콘텐츠 목록을 빈 목록으로 초기화해야합니다 (null 일 수 없음).

예 :

[ContentProperty("Items")] 
public class CustomControl : UserControl 
{ 

    public static readonly DependencyProperty ItemsProperty = 
     DependencyProperty.Register("Items", typeof(UIElementCollection), typeof(CustomControl), new UIPropertyMetadata(null))); 

    public UIElementCollection Items  
    {  
     get { return (UIElementCollection) GetValue(ItemsProperty); }  
     set { SetValue(ItemsProperty, value); }  
    } 

    public CustomControl() 
    { 
     Items = new UIElementCollection(); 
    } 

} 

중요 : 때문에

... new UIPropertyMetadata(new UIElementCollection()) 

이 고려 나쁜 관행 :는 종속성 속성 등록 내부의 빈 컬렉션을 만들하지 마십시오, 즉이를 사용하지 않는 그런 다음 의도하지 않게 싱글 톤 컬렉션을 생성합니다. 자세한 내용은 Collection-Type Dependency Properties을 참조하십시오.

관련 문제