WPF-xaml 计算文本框值的总数 [英] WPF-xaml Calculating Total of text box values

查看:12
本文介绍了WPF-xaml 计算文本框值的总数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a wpf xaml form which has 5 text boxes shows order price. Below the 5 text boxes i have another textbox:[subTotal] which displays the subtotal of order price's."SubTotal" Textbox should display the subtotal of order prices automatically.

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

Is there any XAMl coding way where i can calculate and dispaly total in the "SubTotal" text box automatically, when user enters a value in the order prices text boxes.

推荐答案

使用这个转换器:

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();
    }
}

这样做:

<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>

看起来像:

这篇关于WPF-xaml 计算文本框值的总数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆