Hwan'Story › @kim-hwan

WPF Freezable을 이용한 DataContext 상속 트릭

· (수정 ) · 조회 363

WPF_Freezable_DataContext_Thumbnail.png

WPF DataContext를 상속하는 Collection 타입의 Attached Property 사용하기

WPF 에서 Attached Property 를 정의하여 사용하는 중 XAML 에서 해당 속성을 사용 시 바인딩이 적용되지 않는 문제를 발견했다.

문제가 되는 코드의 일부는 아래와 같다.

/// CS

public class KeyGestureCommand : DependencyObject
{
    public static readonly DependencyProperty GestureProperty =
        DependencyProperty.Register
        (
            name: nameof(Gesture),
            propertyType: typeof(KeyGesture),
            ownerType: typeof(KeyGestureCommand),
            typeMetadata: new FrameworkPropertyMetadata(null)
        );

...
...
...

    public static readonly DependencyProperty CommandProperty =
        DependencyProperty.Register
        (
            name: nameof(Command),
            propertyType: typeof(ICommand),
            ownerType: typeof(KeyGestureCommand),
            typeMetadata: new FrameworkPropertyMetadata(null)
        );
    
...
...
...
}


public static readonly DependencyProperty CommandGesturesProperty =
    DependencyProperty.RegisterAttached
    (
        name: "ShadowCommandGestures",
        propertyType: typeof(Collection<KeyGestureCommand>),
        ownerType: typeof(KeyboardBehavior),
        defaultMetadata: new FrameworkPropertyMetadata(null)
    );

...
...
...

/// XAML

<Grid>
    <BLABLA.CommandGestures>
        <KeyGestureCommand Gesture="F5" Command="{Binding TestCommand}" />
    </BLABLA.CommandGestures>
</Grid>

위 코드 실행 시 Grid의 CommandGestures 속성에 들어있는 KeyGestureCommand의 Command 속성의 값이 null이다. 바인딩이 동작하지 않는 것이다.

바인딩이 동작하지 않는 원인 자체는 간단한데 바인딩이 작동하기 위해서는 트리 내에서 종속성 객체의 위치에 따라서 DataContext 바인딩이 동작하기 때문이다. 그런데 현재 동작하지 않는 속성의 값은 트리에 존재하지 않고 단순히 특정 객체의 값일 뿐이다.

해결방법

결론만 말하면 속성의 타입이 Freezable을 상속하도록 만들면 동작한다. Freezable 클래스는 특별한 동작 매커니즘을 가지고 있어서 실제 시각/논리 트리에 없을 때에도 DataContext를 상속한다는 점이다. (이렇게 동작하는 명확한 이유를 찾으려 했으나 찾지 못했다.)

Freezable 클래스를 상속하면 해결되므로, Collection 타입의 속성을 FreezableCollection 을 상속하는 별도의 클래스로 만들고 하위 항목 클래스도 Freezable 클래스를 상속하도록 변경하니 정상적으로 바인딩이 동작했다.

참고

https://drwpf.com/blog/2008/05/22/leveraging-freezables-to-provide-an-inheritance-context-for-bindings/

https://thomaslevesque.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/

https://siderite.dev/blog/collection-attached-properties-with.html

관련 게시글