如何:绑定到方法

以下示例演示如何使用 ObjectDataProvider 绑定到方法。

示例

在本示例中,TemperatureScale 是一个具有方法 ConvertTemp 的类,该方法接收两个参数(分别为 doubleenum 类型的 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 绑定到方法的两个参数。 这允许用户指定要转换的温度以及要转换自的温标。 请注意,BindsDirectlyToSource 设置为 true,因为我们要绑定到 ObjectDataProvider 实例的 MethodParameters 属性,而不是绑定到由 ObjectDataProvider 包装的对象(TemperatureScale 对象)的属性。

用户修改 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 接收一个 double 类型,并以 Convert 方向(从绑定源到绑定目标,绑定目标是 Text 属性)将其转换为 string 类型,并以 ConvertBack 方向将 string 转换为 double

InvalidationCharacterRule 是一个 ValidationRule,用于检查无效字符。 默认的错误模板是一个围绕在 TextBox 四周的红色边框,用于在输入值不是一个 double 类型的值时向用户发出通知。

另请参阅