wpf 中列表框的值的总和
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17880399/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sum of values of a listbox in wpf
提问by Abhinav
I have a TextBoxin WPF and a ListBox. ListBox(listAmount) is containing some values and I want the sum of that values in that TextBox(txtTotalAmount).
我有一个TextBoxWPF 和一个ListBox. ListBox(listAmount) 包含一些值,我想要这些值的总和TextBox(txtTotalAmount)。
I am using currently this code:
我目前正在使用此代码:
int i = 0;
int sum = 0;
for (i = 0; i < listAmount.Items.Count; i++)
{
sum = sum + Convert.ToInt32(listAmount.Items[i]);
}
txtTotalAmount.Text = sum.ToString();
And I get this error:
我收到这个错误:
Unable to cast object of type 'System.Windows.Controls.ListBoxItem' to type 'System.IConvertible'
无法将“System.Windows.Controls.ListBoxItem”类型的对象转换为“System.IConvertible”
I will be greatfull to you.
我会对你很满意。
回答by O. R. Mapper
The error message explains that listAmount.Items[i]returns instances of type ListBoxItem. That class is derived from ContentControl, which is why its Contentpropertyshould contain the actual value you are looking for.
错误消息解释了listAmount.Items[i]返回类型的实例ListBoxItem。该类派生自ContentControl,这就是为什么它的Content属性应该包含您正在寻找的实际值。
Therefore, try:
因此,请尝试:
sum += Convert.ToInt32(((ListBoxItem)listAmount.Items[i]).Content);
The typecast is necessary because the indexer of ItemCollectionis typed to object.
类型转换是必要的,因为 的索引器ItemCollection类型为object。
That said, have you tried using a collection (e.g. an ObservableCollection<int>) to store your values and set that collection as the ItemsSourceof your listbox? You could then directly grab and sum up the integer values from your collection without the necessity to convert anything.
也就是说,您是否尝试过使用集合(例如 an ObservableCollection<int>)来存储您的值并将该集合设置为ItemsSource列表框的 ?然后,您可以直接从您的集合中获取和总结整数值,而无需转换任何内容。
Add this declaration to your window to store a list of integer values:
将此声明添加到您的窗口以存储整数值列表:
private readonly ObservableCollection<int> values = new ObservableCollection<int>();
Then, after your call to InitializeComponents, assign the ItemsSourceproperty:
然后,在您调用 之后InitializeComponents,分配ItemsSource属性:
listAmount.ItemsSource = values;
Add and remove your values to and from the valueslist whenever you like then; the contents of the list will always be reflected by the listbox.
随时在values列表中添加和删除您的值;列表的内容将始终由列表框反映。
For retrieving the sum of those values, you can then simply use the following:
为了检索这些值的总和,您可以简单地使用以下内容:
int sum = values.Sum();
Note that the System.Linqnamespaceneeds to be included with a usingdirective for this to work, or the Summethodwill not be found.)
请注意,System.Linq命名空间需要包含一个using指令才能使其工作,否则将找不到该Sum方法。)
回答by lightxx
I would recommend another approach that blends better to WPF / XAML.
我会推荐另一种与 WPF/XAML 更好地融合的方法。
Use a binding on your Textbox.Text, and create a property in your object that you bind to. Perform the math in the getter of the property. I would restrain from manually assigning the Textbox.Text value every time it changes. Binding is one of WPFs biggest advantages VS Winforms.
在 Textbox.Text 上使用绑定,并在绑定到的对象中创建一个属性。在属性的 getter 中执行数学运算。我会限制每次更改时手动分配 Textbox.Text 值。绑定是 WPF VS Winforms 的最大优势之一。
This of course requires that your object implements the INotifyPropertyChanged interface. http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx
这当然要求您的对象实现 INotifyPropertyChanged 接口。http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx
EDIT: IF you absolutely have to do it without bindings that i'd recommend summing up using a LINQ query. Simple and elegant (for this example my ListBox has an ItemSource that is an array if integers. You would of course have to adapt the Cast<> to whatever you are using).
编辑:如果您绝对必须在没有绑定的情况下执行此操作,我建议您使用 LINQ 查询进行总结。简单而优雅(在这个例子中,我的 ListBox 有一个 ItemSource,它是一个数组,如果是整数。你当然必须使 Cast<> 适应你正在使用的任何东西)。
var numbers = new[] { 1, 2, 3, 4, 5, 6 };
var listBox = new ListBox {ItemsSource = numbers};
var sum = listBox.Items.Cast<int>().Sum();
回答by Sayse
If you know that they will always be integers you can use Linq
如果您知道它们始终是整数,则可以使用 Linq
listAmmount.Items.Cast<string>().Sum(x => int.Parse(x)).ToString();
Edit
编辑
Tested in wpf
在 wpf 中测试
textBox1.Text = listBox1.Items.Cast<ListBoxItem>().Sum(x => Convert.ToInt32(x.Content)).ToString();
回答by Giannis Paraskevopoulos
Use :
用 :
listAmount.Items[i].ToString()
回答by Malcor
There Is probably a much cleaner way of doing it, but this
可能有一种更清洁的方法,但是这个
var items = listAmount.Items;
int SUM;
foreach (var item in items)
{
int itemvalue = Convert.ToInt32(item.ToString());
SUM += itemvalue;
}

