我的问题如下。
我有 3 个文本框绑定到数据集中的 3 个字段。TextBox_Rate,TextBox_Hours,TextBox_Salary。
我需要的是TextBox_Rate + TextBox_Hours = TextBox_Salary。
我发现这可以通过使用Multibinding和Converter来实现。
多重绑定如下所示:
<TextBox FontSize="14.667" HorizontalAlignment="Right" HorizontalContentAlignment="Right" Style="{StaticResource TextBoxStyle}">
<TextBox.Text>
<MultiBinding Converter="{StaticResource SalaryConverter}" UpdateSourceTrigger="PropertyChanged" Mode="TwoWay" ValidatesOnExceptions="True" NotifyOnValidationError="True" NotifyOnSourceUpdated="True" StringFormat="C">
<Binding Path="Rate Per Hour"/>
<Binding Path="Hours Per Month"/>
</MultiBinding>
</TextBox.Text>
</TextBox>
和转换器:
Public Class SalaryConverter
Implements IMultiValueConverter
Dim weeklyHours As Double = 0
Public Function Convert(ByVal values() As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IMultiValueConverter.Convert
Dim salary As Decimal = 0
If values(0).Equals(System.Windows.DependencyProperty.UnsetValue) Or values(1).Equals(System.Windows.DependencyProperty.UnsetValue) Then
Return salary
Else
salary = (Math.Round(values(0) * (values(1) * 4)))
weeklyHours = values(1)
Return salary
End If
End Function
Public Function ConvertBack(ByVal value As Object, ByVal targetTypes() As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object() Implements System.Windows.Data.IMultiValueConverter.ConvertBack
Dim testVal As Decimal = CType((value.ToString.Replace("R ", "").Replace(",", "") / weeklyHours), Decimal) / 4
Return New Object() {testVal}
End Function
结束类
所有这些都 100% 有效。我得到了我想要的结果。但这也是问题所在……
TextBox_Rate绑定到 Dataset 字段Rate,TextBox_Hours绑定到 Dataset 字段Hours并且最初(在多重绑定之前)TextBox_Salary绑定到 Dataset 字段Salary但现在绑定到TextBox_Rate AND TextBox_Hours。并且从 Multibinding 生成的值不会更新回源字段“Salary”,因为它没有绑定该字段。
如何设置绑定以更新该字段?
提前致谢。