共用方式為


HOW TO:繫結至方法

下列範例顯示如何使用 ObjectDataProvider 繫結至方法。

範例

在此範例中,TemperatureScale 為具有方法 ConvertTemp 的類別,它採用兩個參數 (一個屬於 double 型別,另一個屬於 enum 型別 TempType),並會將指定值從某個溫標轉換為另一個溫標。 在下列範例中,將使用 ObjectDataProvider 來具現化 (Instantiate) 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 會採用雙精度浮點數,並依照 Convert 方向 (從繫結來源至繫結目標,其為 Text 屬性) 將其轉換成字串,並依照 ConvertBack 方向將 string 轉換成 double。

InvalidationCharacterRule 是一個可檢查字元是否有效的 ValidationRule。 預設的錯誤範本為紅色框線圍著 TextBox,當輸入值不是雙精度浮點數值時便會顯示,以告知使用者。

請參閱

工作

HOW TO:繫結至列舉

其他資源

資料繫結 HOW TO 主題