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

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

使用例

この例では、TemperatureScale はメソッド ConvertTemp を持つクラスで、2 つのパラメーター (1 つは double でもう 1 つは enum 型 TempType) を取得して、指定した値をある温度尺度から他の温度尺度へ変換します。 次の例では、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 つのパラメーターにバインドします。 これにより、ユーザーは、変換する温度と変換前の温度尺度を指定できます。 BindsDirectlyToSource が true に設定されることに注意してください。これは、ObjectDataProvider (TemperatureScale オブジェクト) によってラップされたオブジェクトのプロパティではなく、ObjectDataProvider インスタンスの MethodParameters プロパティにバインドするためです。

最後の LabelContent は、ユーザーが TextBox の内容、または ComboBox の選択を変更したときに更新されます。

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

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

参照

処理手順

方法 : 列挙値にバインドする

その他の技術情報

データ バインディングに関する「方法」トピック