操作說明:繫結至方法
下列範例示範如何使用 系結至 方法 ObjectDataProvider 。
範例
在此範例中,TemperatureScale
是一個包含方法 ConvertTemp
的類別,它接受兩個參數 (一個是 double
類型,一個是 enum
類型 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>
現在,方法已經成為資源,就可以繫結至其結果。 在下列範例中, Text 和 SelectedValue 的 ComboBox 屬性 TextBox 會系結至 方法的兩個參數。 這可讓使用者指定要轉換的溫度及轉換前的溫度單位。 請注意,是設定為 true
, BindsDirectlyToSource 因為我們系結至 MethodParameters 實例的 ObjectDataProvider 屬性,而不是 由 ObjectDataProvider ( TemperatureScale
物件) 包裝之物件的屬性。
Content當使用者修改 TextBox 的內容或 選取範圍時,上次 Label 更新的 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 字串(從系結來源到系結目標,也就是 Text 屬性),並將 轉換成 string
double
方向的 ConvertBack 。
InvalidationCharacterRule
是 ValidationRule 檢查無效字元的 。 預設錯誤範本,也就是 周圍的 TextBox 紅色框線,在輸入值不是雙精度浮點值時,會顯示通知使用者。
另請參閱
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應