다음을 통해 공유


x:Bind의 함수

비고

{x:Bind}을 사용하여 앱에서 데이터 바인딩을 적용하는 방법에 대한 일반적인 정보(및 {x:Bind}{Binding}간의 전체 비교를 위해서는 데이터 바인딩 심층 분석{x:Bind} 마크업 확장을 참조하세요.

Windows 10 버전 1607부터 {x:Bind} 함수를 바인딩 경로의 리프 단계로 사용할 수 있습니다. 이렇게 하면 다음을 수행할 수 있습니다.

  • 값 변환을 수행하는 더 간단한 방법
  • 바인딩이 둘 이상의 매개 변수에 의존하는 방법

비고

{x:Bind}함수를 사용하려면 앱의 최소 대상 SDK 버전은 14393 이상이어야 합니다. 앱이 이전 버전의 Windows 10을 대상으로 하는 경우 함수를 사용할 수 없습니다. 대상 버전에 대한 자세한 내용은 버전 적응 코드참조하세요.

다음 예제에서 항목의 배경 및 전경은 색 매개 변수에 따라 변환을 수행하는 함수에 바인딩됩니다.

<DataTemplate x:DataType="local:ColorEntry">
    <Grid Background="{x:Bind local:ColorEntry.Brushify(Color), Mode=OneWay}" Width="240">
        <TextBlock Text="{x:Bind ColorName}" Foreground="{x:Bind TextColor(Color)}" Margin="10,5" />
    </Grid>
</DataTemplate>
class ColorEntry
{
    public string ColorName { get; set; }
    public Color Color { get; set; }

    public static SolidColorBrush Brushify(Color c)
    {
        return new SolidColorBrush(c);
    }

    public SolidColorBrush TextColor(Color c)
    {
        return new SolidColorBrush(((c.R * 0.299 + c.G * 0.587 + c.B * 0.114) > 150) ? Colors.Black : Colors.White);
    }
}

XAML 속성 사용

<object property="{x:Bind pathToFunction.FunctionName(functionParameter1, functionParameter2, ...), bindingProperties}" ... />

함수 경로

함수의 경로는 다른 속성 경로와 마찬가지로 지정되며, (.)이나 인덱서, 또는 캐스트를 포함할 수 있습니다. 이러한 요소들을 사용하여 함수를 찾을 수 있습니다.

XMLNamespace:ClassName.MethodName 구문을 사용하여 정적 함수를 지정할 수 있습니다. 예를 들어, 코드 비하인드에서 정적 함수에 바인딩하기 위해 아래 구문을 사용합니다.

<Page 
     xmlns:local="using:MyNamespace">
     ...
    <StackPanel>
        <TextBlock x:Name="BigTextBlock" FontSize="20" Text="Big text" />
        <TextBlock FontSize="{x:Bind local:MyHelpers.Half(BigTextBlock.FontSize)}" 
                   Text="Small text" />
    </StackPanel>
</Page>
namespace MyNamespace
{
    static public class MyHelpers
    {
        public static double Half(double value) => value / 2.0;
    }
}

마크업에서 직접 시스템 함수를 사용하여 날짜 서식, 텍스트 서식, 텍스트 연결 등의 간단한 시나리오를 수행할 수도 있습니다. 예를 들어:

<Page 
     xmlns:sys="using:System"
     xmlns:local="using:MyNamespace">
     ...
     <CalendarDatePicker Date="{x:Bind sys:DateTime.Parse(TextBlock1.Text)}" />
     <TextBlock Text="{x:Bind sys:String.Format('{0} is now available in {1}', local:MyPage.personName, local:MyPage.location)}" />
</Page>

방식이 OneWay/TwoWay인 경우, 함수 경로에서 변경 감지가 수행되고, 해당 개체에 변경사항이 있으면 바인딩이 다시 평가됩니다.

바인딩되는 함수는 다음을 수행해야 합니다.

  • 코드 및 메타데이터에 액세스할 수 있으므로 C#에서 내부/프라이빗 작업을 수행하지만 C++/CX는 공용 WinRT 메서드가 되려면 메서드가 필요합니다.
  • 오버로딩은 형식이 아닌 인수 수를 기반으로 하며, 첫 번째 오버로드와 해당 인수를 일치시키려고 시도합니다.
  • 인수 형식은 전달되는 데이터와 일치해야 합니다. 축소 변환은 수행하지 않습니다.
  • 함수의 반환 형식은 바인딩을 사용하는 속성의 형식과 일치해야 합니다.

바인딩 엔진은 함수 이름으로 발생한 속성 변경 알림에 반응하고 필요에 따라 바인딩을 다시 평가합니다. 다음은 그 예입니다.

<DataTemplate x:DataType="local:Person">
   <StackPanel>
      <TextBlock Text="{x:Bind FullName}" />
      <Image Source="{x:Bind IconToBitmap(Icon, CancellationToken), Mode=OneWay}" />
   </StackPanel>
</DataTemplate>
public class Person : INotifyPropertyChanged
{
    //Implementation for an Icon property and a CancellationToken property with PropertyChanged notifications
    ...

    //IconToBitmap function is essentially a multi binding converter between several options.
    public Uri IconToBitmap (Uri icon, Uri cancellationToken)
    {
        Uri foo = new Uri(...);        
        if (isCancelled)
        {
            foo = cancellationToken;
        }
        else 
        {
            if (this.fullName.Contains("Sr"))
            {
               //pass a different Uri back
               foo = new Uri(...);
            }
            else
            {
                foo = icon;
            }
        }
        return foo;
    }

    //Ensure FullName property handles change notification on itself as well as IconToBitmap since the function uses it
    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
        }
    }
}

팁 (조언)

x:Bind의 함수를 사용하여 WPF의 변환기 및 MultiBinding을 통해 지원된 것과 동일한 시나리오를 달성할 수 있습니다.

함수 인수

쉼표(,)로 구분하여 여러 함수 인수를 지정할 수 있습니다.

  • 바인딩 경로 – 해당 개체에 직접 바인딩하는 것과 동일한 구문입니다.
    • 모드가 OneWay 또는 TwoWay인 경우 변경 감지가 수행되고, 개체 변경 시 바인딩이 다시 평가됩니다.
  • 따옴표로 묶인 상수 문자열 – 문자열로 지정하려면 따옴표가 필요합니다. 문자열에서 따옴표를 이스케이프하는 데 Hat(^)을 사용할 수 있습니다.
  • 상수 번호 - 예: -123.456
  • 불리언 – "x:True" 또는 "x:False"로 지정됨

팁 (조언)

TargetNullValue 는 바인딩된 인수가 아니라 함수 호출 결과에 적용됩니다.

양방향 함수 바인딩

양방향 바인딩 시나리오에서는 바인딩의 역방향에 대해 두 번째 함수를 지정해야 합니다. 이 작업은 BindBack 바인딩 속성을 사용하여 수행됩니다. 아래 예제에서 함수는 모델로 다시 푸시해야 하는 값인 인수 하나를 사용해야 합니다.

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

참고하십시오

  • {x:Bind} 마크업 확장