方法: メソッドにバインドする

次の例では、ObjectDataProvider を使用してメソッドにバインドする方法を示します。

この例では、TemperatureScale はメソッド ConvertTemp を持つクラスで、2 つのパラメーター (1 つは double でもう 1 つは enumTempType)) を取得して、指定した値をある温度尺度から他の温度尺度へ変換します。 次の例では、ObjectDataProvider を使用して TemperatureScale オブジェクトをインスタンス化する方法を示します。 ConvertTemp メソッドは、2 つの指定したパラメーターで呼び出されます。

<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 を、メソッドの 2 つのパラメーターにバインドします。 これにより、ユーザーは、変換する温度と変換前の温度尺度を指定できます。 ObjectDataProvider によってラップされたオブジェクト (TemperatureScale オブジェクト) のプロパティではなく、ObjectDataProvider インスタンスの MethodParameters プロパティにバインドしているため、BindsDirectlyToSourcetrue に設定されていることに注意してください。

ユーザーが 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 のとき (バインディング ソースからバインディング ターゲット、これは Text プロパティです) は double を受け取って string に変換し、方向が ConvertBack のときは stringdouble に変換します。

InvalidationCharacterRule は、無効な文字をチェックする ValidationRule です。 入力値が double 値でない場合は、既定のエラー テンプレート (TextBox を囲む赤い境界線) がユーザーへの通知として表示されます。

関連項目