TwoContentsButton.cs : 의존 속성
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public class TwoContentsButton : Button { #region SecondContent : 두번째 Content public string SecondContent { get { return (string)GetValue(SecondContentProperty); } set { SetValue(SecondContentProperty, value); } } public static readonly DependencyProperty SecondContentProperty = DependencyProperty.Register( "SecondContent", typeof(string), typeof(TwoContentsButton), new PropertyMetadata(string.Empty)); #endregion } | cs |
Button 컨트롤을 상속 받아서 TwoContentsButton이라는 새로운 컨트롤을 만드는 방법입니다. 이전 포스트에서 알아본 Dependency Property를 이용해 두번째 Content 속성을 추가할 수 있습니다.
1 | xmlns:ctr="clr-namespace:Sample.Control" | cs |
새 컨트롤을 만든 것이므로 XAML에서 사용하려면 네임스페이스 추가가 필요합니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <ctr:TwoContentsButton Content="Menu03" Margin="20" Grid.Column="2"> <Button.Template> <ControlTemplate TargetType="Button"> <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}"> <StackPanel HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" Margin="5"> <ContentPresenter Content="{TemplateBinding Content}"/> <TextBlock Text=" " TextWrapping="Wrap"/> </StackPanel> </Border> </ControlTemplate> </Button.Template> </ctr:TwoContentsButton> | cs |
기존 버튼도 새 버튼에 맞춰 변경해야 합니다. 점점 수정해야 할 것들이 늘어납니다.
빌드 과정을 거친 후에는 IntelliSense에 도움을 받아 SecondContent 속성을 정의할 수 있습니다.
1 | <TextBlock Text="{TemplateBinding SecondContent}" TextWrapping="Wrap"/> | cs |
의존 속성을 정의한 후에는 두번째 Content 역할을 할 TextBlock과 연결해줘야 겠습니다. 기존 ContentPresenter처럼 TemplateBinding 문법을 사용할 수는 없습니다. 빌드 자체가 되지 않습니다.
1 | <TextBlock Text="{Binding SecondContent, RelativeSource={RelativeSource TemplatedParent}}" TextWrapping="Wrap"/> | cs |
Binding 문법에서 템플릿 부모를 Source로 지정하는 방법으로 SecondContent 속성에 접근할 수 있습니다.
샘플 코드 : https://github.com/CharlesKwon/XamlSimplified
관련 목차
015. 두개의 컨텐츠 버튼(Two contents button) #1
016. 두개의 컨텐츠 버튼(Two contents button) #2
017. 두개의 컨텐츠 버튼(Two contents button) #3
'XAML 뽀개기' 카테고리의 다른 글
018. 컨트롤템플릿(ControlTemplate) #1 (0) | 2018.02.12 |
---|---|
017. 두개의 콘텐츠 버튼(Two Contents Button) #3 (0) | 2018.02.05 |
016. 두개의 콘텐츠 버튼(Two Contents Button) #2 (0) | 2018.02.02 |
015. 두개의 콘텐츠 버튼(Two Contents Button) #1 (0) | 2018.01.31 |
014. 결합 속성(Attached property) (0) | 2018.01.28 |
013. 속성 상속(Resolved Dynamically) (0) | 2018.01.24 |