如何绑定方法

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

示例:

在此示例中,TemperatureScale是一个具有方法ConvertTemp的类,该方法接收两个参数(其中一个是double类型,另一个是enumTempType)类型),并将给定值从一个温度刻度转换为另一个温度刻度。 在以下示例中,一个 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选择时,最后一次Label更新的Content

<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属性),同时在ConvertBack方向将string转换为double

InvalidCharacterRule 是一种 ValidationRule,用于检查无效字符。 默认错误模板是红色 TextBox边框,在输入值不是双精度值时,会显示通知用户。

另请参阅