[WinUI 3] x:Bind 태그 확장 탐구

개요

WinUI에서는 데이터를 바인딩할 때 {Binding} 확장 보다는 {x:Bind}를 사용하는 것을 권장합니다. {Binding}과의 차이점을 통해 간략히 {x:Bind}의 사용법과 특징을 알아봅시다.

{Binding}와의 차이점

컴파일 타임 코드 생성

가장 큰 차이점은 {Binding}은 동적으로 바인딩을 처리 하고 {x:Bind}는 코드 생성기를 통해 바인딩을 처리한다는 점입니다. 약간의 성능 상승이 있을 것 같습니다.

메서드 바인딩

{Binding}도 메서드 바인딩이 가능하지만 복잡하고 제한이 있었습니다. {x:Bind}는 메서드 바인딩을 쉽게 사용할 수 있습니다.

<TextBlock FontSize="{x:Bind local:MyHelpers.Half(BigTextBlock.FontSize)}" 
                   Text="Small text" />

메서드 바인딩에서 OnwWay 동작은 메소드명으로 OnPropertyChanged()를 호출함으로 가능합니다.

<Image Source="{x:Bind IconToBitmap(Icon, CancellationToken), Mode=OneWay}" />
    public string FullName
    {
        get { return this.fullName; }
        set
        {
            this.fullName = value;
            this.OnPropertyChanged ();
            this.OnPropertyChanged ("IconToBitmap"); 
            //this ensures Image.Source binding re-evaluates when FullName changes in addition to Icon and CancellationToken
        }
    }

메서드 바인딩에도 TwoWay 모드를 사용할 수 있습니다.

<TextBlock Text="{x:Bind a.MyFunc(b), BindBack=a.MyFunc2, Mode=TwoWay}" />

DataContext를 사용하지 않습니다.

{x:Bind}는 DataContext를 사용하지 않고 경로의 루트는 Page입니다. 그래서 ViewModel에 접근할 때는 ViewModel을 속성으로 만들어서 {x:bind ViewModel.xxx}의 패턴을 사용하게 됩니다.

다른 컨트롤의 속성 접근이 간단합니다.

바인딩 루트 경로가 루트 컨트롤이므로 접근하고자 하는 컨트롤의 속성 접근을 다음처럼 쉽게 할 수 있습니다.

            <ListView x:Name="leftListView" Grid.Column="0" ItemsSource="{x:Bind ViewModel.LeftEntityVisuals, Mode=OneTime}" SelectionMode="Multiple" DisplayMemberPath="Reference.LogicalName" BorderThickness="1" BorderBrush="{ThemeResource SystemControlForegroundBaseMediumLowBrush}" />
            <StackPanel Grid.Column="1" Orientation="Vertical" VerticalAlignment="Center" Spacing="4">
                <Button Command="{x:Bind ViewModel.MoveAllRightCommand}" CommandParameter="{x:Bind leftListView.SelectedItems, Mode=OneTime}">
                    <FontIcon FontFamily="{StaticResource SymbolThemeFontFmaily}" Glyph="&#xede1;"/>
                </Button>
...

CommandParameter="{x:Bind leftListView.SelectedItems, Mode=OneTime}" 처럼 커맨드 인자로 컨트롤 속성값을 쉽게 넘길수 있습니다.

4개의 좋아요