来自文本框的WPF总和值

时间:2016-08-23 09:28:02

标签: wpf

我有5个TextBox用于编号。我想在写完后显示文本框中的总和数字。目前显示文本框中的数字,而不是总和。这是我的代码:

<StackPanel Orientation="Vertical" Margin="0 10 24 0" DockPanel.Dock="Right" HorizontalAlignment="Right">
        <TextBlock Text="Hc" HorizontalAlignment="Center"></TextBlock>
        <ItemsControl ItemsSource="{Binding Path=List}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding Path=Value, Mode=TwoWay}" PreviewTextInput="NumberValidationTextBox" Width="50"/>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
        <Button Command="{Binding SaveCommand}" Style="{StaticResource SmallSuccessButton}" Margin="0 10 0 0" Content="Save"></Button>
    </StackPanel>

    <StackPanel Orientation="Vertical" Margin="0 10 5 0" DockPanel.Dock="Right" HorizontalAlignment="Right">
        <TextBlock Text="Sum" HorizontalAlignment="Center"></TextBlock>
        <ItemsControl ItemsSource="{Binding Path=List}" HorizontalContentAlignment="Center">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal" Background="red">
                        <TextBlock Text="{Binding Path=Value, Mode=OneWay}" Height="26" PreviewTextInput="NumberValidationTextBox" 
                                   Width="60" 
                                   HorizontalAlignment="Center" />
                    </StackPanel>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </StackPanel>

在ViewModel中:  private ObservableCollection _list;

    public ObservableCollection<Data> List
    {
        get { return _list;}
        set { _list = value; OnPropertyChanged(nameof(List)); }
    }



    public class MeasureInput
    {
        public float Value { get; set; }

        public MeasureInput(float f)
        {

        }
    }

结果必须是:

SUM文本框 10我写10和总和10 15我写5和总和15

由于

2 个答案:

答案 0 :(得分:1)

将此代码添加到ViewModel:

public double Sum
{
    get { return List.Sum();}
}

在您的XAML中,绑定到Sum而不是List:

 <TextBlock Text="{Binding Sum}" />

答案 1 :(得分:1)

添加到stackpanel

<StackPanel  TextBox.TextChanged="OnTextChanged">
....


</StackPanel>

然后在代码背后

public void OnTextChanged(routedEvent e,sender variable)
{
int Sum = 0;
    if(e.source is TextBox)
    {
      forearch(Child child in stackpanel.Children)
        {
              if(child is TextBox)
              {
                  TextBox txt = child as TextBox;
                  if(txt.Text  != "") //validation empty textbox
                    Sum+= int.Parse(txt.Text);
               }
        }
    }

}