AttachedProperty.cs : 결합 속성
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | public class AP_TwoContentsButton { #region SecondContent public static readonly DependencyProperty SecondContentProperty = DependencyProperty.RegisterAttached( "SecondContent", typeof(string), typeof(AP_TwoContentsButton), new PropertyMetadata(string.Empty)); public static string GetSecondContent(DependencyObject dp) { return (string)dp.GetValue(SecondContentProperty); } public static void SetSecondContent(DependencyObject dp, string value) { dp.SetValue(SecondContentProperty, value); } #endregion } | cs |
이번엔 Attached Property를 이용해 봅시다. 먼저 Dependency Property와는 달리 Button 컨트롤을 상속 받을 필요 없이 새로운 클래스를 만들었습니다. 이전 Class 명과 구분하기 위해 보기는 싫지만 AP_를 덧붙여 작성했습니다.
1 | xmlns:atcp="clr-namespace:Sample.AttachedProperty" | cs |
XAML 코드에서 결합 속성을 사용하기 위해 네임스페이스를 추가합니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <Button Content="Menu03" atcp:AP_TwoContentsButton.SecondContent="Lorem Ipsum is simply" 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="{Binding (atcp:AP_TwoContentsButton.SecondContent), RelativeSource={RelativeSource TemplatedParent}}" TextWrapping="Wrap"/> </StackPanel> </Border> </ControlTemplate> </Button.Template> </Button> | cs |
기존 Button 컨트롤에 atcp:AP_TwoContentsButton.SecondContent 결합 속성을 정의합니다. 결합 속성은 [정의타입].[속성명] 형태의 문법을 사용합니다.
1 | <TextBlock Text="{Binding (atcp:AP_TwoContentsButton.SecondContent), RelativeSource={RelativeSource TemplatedParent}}" TextWrapping="Wrap"/> | cs |
이전 의존 속성에서 사용한 TextBlock의 코드를 재사용합니다. Binding 문법의 Path 속성만 추가한 결합속성에 알맞게 수정합니다. 간혹 Visual Studio에서 에러가 발생하는데 VS를 끄고 다시 켜면 에러가 나지 않습니다. 제 생각에는 버그인 듯 합니다.
동일한 표현이 가능합니다.
왼쪽이 결합 속성, 오른쪽이 의존 속성입니다. 결합 속성과 의존 속성을 속성 창에서 찾아 비교해보면 의존 속성만 노출되는 것을 알 수 있습니다. 당연한 결과라 생각할 수 있습니다. 결합 속성은 자신이 정의된 클래스가 아닌 다른 클래스에서 적용될 수 있다는 점이 다릅니다. 이전 결합 속성 포스트에서 레이아웃을 정의하는데 사용된다고 이야기했었습니다.
결합 속성은 레이아웃 정의 뿐만 아니라 무한 확장 기능 구현에 큰 기능을 합니다. 좀 더 속 깊은 설명은 박문찬 MVP님의 블로그 포스트를 참고하시면 좋을 듯 합니다.
Dependency Property와 Attached Property의 차이점이 뭐지? #1
Dependency Property와 Attached Property의 차이점이 뭐지? #2
샘플 코드 : https://github.com/CharlesKwon/XamlSimplified
관련 목차
015. 두개의 컨텐츠 버튼(Two contents button) #1
016. 두개의 컨텐츠 버튼(Two contents button) #2
017. 두개의 컨텐츠 버튼(Two contents button) #3
'XAML 뽀개기' 카테고리의 다른 글
019. 컨트롤템플릿(ControlTemplate) #2 (0) | 2018.02.12 |
---|---|
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 |