WPF-xaml计算文本框值的总和

SNA*_*SNA 3 wpf textbox

我有一个wpf xaml表单,其中有5个文本框显示订单价格.在5个文本框下方,我有另一个文本框:[subTotal]显示订单价格的小计."SubTotal"文本框应自动显示订单价格的小计.

当用户在订单价格文本框中输入值时,是否有任何XAMl编码方式,我可以在"SubTotal"文本框中自动计算和显示总计.

Jer*_*xon 10

使用此转换器:

public class SumConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType,
        object parameter, System.Globalization.CultureInfo culture)
    {
        double _Sum = 0;
        if (values == null)
            return _Sum;
        foreach (var item in values)
        {
            double _Value;
            if (double.TryParse(item.ToString(), out _Value))
                _Sum += _Value;
        }
        return _Sum;
    }

    public object[] ConvertBack(object value, Type[] targetTypes,
        object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
Run Code Online (Sandbox Code Playgroud)

做这个:

<Window.Resources>
    <local:SumConverter x:Key="MySumConverter" />
</Window.Resources>
<StackPanel>
    <TextBox Name="TextBox1" Text="1" />
    <TextBox Name="TextBox2" Text="2" />
    <TextBox Name="TextBox3" Text="3" />
    <TextBox Name="TextBox4" Text="4" />
    <TextBox Name="TextBox5" Text="5" />
    <TextBlock>
        <TextBlock.Text>
            <MultiBinding Converter="{StaticResource MySumConverter}"
                          StringFormat="{}{0:C}"
                          FallbackValue="Error" TargetNullValue="Null">
                <Binding Path="Text" ElementName="TextBox1" />
                <Binding Path="Text" ElementName="TextBox2" />
                <Binding Path="Text" ElementName="TextBox3" />
                <Binding Path="Text" ElementName="TextBox4" />
                <Binding Path="Text" ElementName="TextBox5" />
            </MultiBinding>
        </TextBlock.Text>
    </TextBlock>
</StackPanel>
Run Code Online (Sandbox Code Playgroud)

好像:

截图