【发布时间】:2020-03-10 03:23:52
【问题描述】:
我想制作一个 wpf 程序,当您单击“生成”按钮时,SSales 类将获取/存储值数组到该类,然后将其返回到列表框。新来的。对不起。
private void GenerateButton_Click(object sender, EventArgs e)
{
Random rand = new Random();
int[] year = { 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 };
double[] Sales = new double[10];
for (int i = 0; i < 10; i++)
{
Sales[i] = rand.Next(1000, 50000);
}
SSales yearSale = new SSales(year, Sales);
for (int j = 0; j < 10; j++){
//I want the listbox to display the values of yearSale.Year and yearSale.Sales
listBox1.Items.Add(yearSale);
}
}
public class SSales
{
public int[] Year { get; set; }
public double[] Sales { get; set; }
public SSales(int[] iYear, double[] dSales)
{
Year = iYear;
Sales = dSales;
}
public override string ToString()
{
//I'm trying to make this format "2001 $25,000.00" then return it to listbox
return string.Format("{0}\t\t{1:C0}", Year, Sales);
}
}
【问题讨论】:
-
我建议创建一个返回格式化字符串的只读属性,而不是覆盖
ToString,然后将ListBox的DisplayMemberPath设置为该属性的名称。 -
有什么问题?不知道是什么问题。
-
listBox1.Items.Add(yearSale.ToString());? -
在 WPF 中,您通常会使用带有两列 GridView 的 ListView。然后将 SSales 类转换为保存 single 年销售额的东西,即两个属性
int Year和double Sales。然后将Sales对象的集合赋给ListView的ItemsSource属性,并在两列模板中绑定这两个属性。从这里开始阅读:Data Templating Overview.