次の方法で共有


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

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

この例では、TemperatureScale はメソッド ConvertTempを持つクラスです。このクラスは、2 つのパラメーター (double の 1 つと enum 型の 1 つ 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>

リソースとしてメソッドを使用できるようになったので、結果にバインドできます。 次の例では、TextTextBox プロパティと SelectedValueComboBox は、メソッドの 2 つのパラメーターにバインドされています。 これにより、ユーザーは変換する温度と変換元の温度スケールを指定できます。 BindsDirectlyToSource は、true (MethodParameters オブジェクト) によってラップされたオブジェクトのプロパティではなく、ObjectDataProvider インスタンスの ObjectDataProvider プロパティにバインドされるため、TemperatureScale に設定されていることに注意してください。

ユーザーが Content の内容または Labelの選択を変更すると、最後の TextBoxComboBox が更新されます。

<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 は double を受け取り、Convert 方向の文字列に変換し (バインディング ソースからバインド ターゲット(Text プロパティ))、stringdouble 方向の ConvertBack に変換します。

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

こちらも参照ください