다음을 통해 공유


방법: 메서드 바인딩

업데이트: 2007년 11월

다음 예제에서는 ObjectDataProvider를 사용하여 메서드를 바인딩하는 방법을 보여 줍니다.

예제

이 예제에서 TemperatureScale은 ConvertTemp라는 메서드를 갖는 클래스입니다. 이 메서드는 두 개의 매개 변수(double 형식과 enum 형식의 TempType)를 사용하고 지정된 값을 한 온도계에서 다른 온도계로 변환합니다. 다음 예제에서는 ObjectDataProvider를 사용하여 TemperatureScale을 인스턴스화합니다. ConvertTemp 메서드는 두 개의 지정된 매개 변수를 호출합니다.

<Window.Resources>
  <ObjectDataProvider ObjectType="{x:Type local:TemperatureScale}"
                      MethodName="ConvertTemp" x:Key="convertTemp">
    <ObjectDataProvider.MethodParameters>
      <system:Double>0</system:Double>
      <local:TempType>Celsius</local:TempType>
    </ObjectDataProvider.MethodParameters>
  </ObjectDataProvider>

  <local:DoubleToString x:Key="doubleToString" />

</Window.Resources>

메서드를 리소스로 사용할 수 있으므로 해당 결과에 바인딩할 수 있습니다. 다음 예제에서는 TextBoxText 속성 및 ComboBoxSelectedValue 속성을 메서드의 두 매개 변수에 바인딩합니다. 이렇게 하면 사용자가 변환할 온도와 변환할 온도계를 지정할 수 있습니다. ObjectDataProvider로 래핑되는(TemperatureScale 개체) 개체의 속성이 아니라 ObjectDataProvider 인스턴스의 MethodParameters 속성에 바딩인하므로 BindsDirectlyToSource는 true로 설정됩니다.

사용자가 TextBox나 선택한 ComboBox의 내용을 수정하면 마지막 LabelContent가 업데이트됩니다.

<Label Grid.Row="1" HorizontalAlignment="Right">Enter the degree to convert:</Label>
<TextBox Grid.Row="1" Grid.Column="1" Name="tb">
  <TextBox.Text>
    <Binding Source="{StaticResource convertTemp}" Path="MethodParameters[0]"
             BindsDirectlyToSource="true" UpdateSourceTrigger="PropertyChanged"
             Converter="{StaticResource doubleToString}">
      <Binding.ValidationRules>
        <local:InvalidCharacterRule/>
      </Binding.ValidationRules>
    </Binding>
  </TextBox.Text>
</TextBox>
<ComboBox Grid.Row="1" Grid.Column="2" 
  SelectedValue="{Binding Source={StaticResource convertTemp},
  Path=MethodParameters[1], BindsDirectlyToSource=true}">
  <local:TempType>Celsius</local:TempType>
  <local:TempType>Fahrenheit</local:TempType>
</ComboBox>
<Label Grid.Row="2" HorizontalAlignment="Right">Result:</Label>
<Label Content="{Binding Source={StaticResource convertTemp}}"
    Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="2"/>

변환기 DoubleToString은 Convert 방향(바인딩 소스를 b바인딩 대상으로, 후자는 Text 속성임)에서는 double를 string으로 변환하고 ConvertBack 방향에서는 string을 double로 변환합니다.

InvalidationCharacterRule은 잘못된 문자가 있는지 검사하는 ValidationRule입니다. 입력 값이 double 값이 아니면 TextBox 주위의 빨간 테두리인 기본 오류 템플릿이 표시되어 사용자에게 알려 줍니다.

전체 예제를 보려면 메서드 결과 바인딩 샘플을 참조하십시오.

참고 항목

작업

방법: 열거형 바인딩

기타 리소스

데이터 바인딩 샘플

데이터 바인딩 방법 항목