案例地址:GitHub - microsoft/WPF-Samples: Repository for WPF related samples
一、运行界面
二、案例功能描述
实现温度单位的转换
三、分析代码
1、温度输入TextBox的数据绑定
在WIndow.Resources中创建ObjectDataProvider:包装和创建可以用作绑定源的对象。
<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>
对TextBox的Text使用方法绑定数据
<TextBox Grid.Row="1" Grid.Column="1" Name="tb">
<TextBox.Text>
<Binding
Source="{StaticResource ConvertTemp}"
Path="MethodParameters[0]" <!-- 路径是参数1 -->
BindsDirectlyToSource="true" <!-- 该值指示是相对于数据项还是DataSourceProvider 对象计算 Path -->
UpdateSourceTrigger="PropertyChanged"
Converter="{StaticResource DoubleToString}">
<Binding.ValidationRules> <!-- 用于检查用户输入有效性的规则的集合 -->
<local:InvalidCharacterRule/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
自定义检查用户输入有效性的规则的集合
InvalidCharacterRule : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
var myvalue = 0.00;
try
{
if (((string) value).Length > 0)
myvalue = double.Parse((string) value);
}
catch (Exception e)
{
return new ValidationResult(false, "Illegal characters or " + e.Message);
}
return new ValidationResult(true, null);
}
}
2、单位选择ComboBox数据绑定
<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>