【问题标题】:Putting two-dimensional array in listbox将二维数组放入列表框中
【发布时间】:2016-01-11 11:44:19
【问题描述】:

所以我有这个数组

string[,] cars = new String[2, 2] { 
                { "VW Golf GTI", "30000" }, 
                { "Porsche GT3", "300000" }, 
                { "Porsche Cayenne", "80000" }, 
                { "BMW M6", "90000" } 
            };

并且想把所有东西都放在一个列表框中,我认为这会起作用,但它没有:/

lstBoxMarket.Items.AddRange(cars);

现在如何将所有内容按格式放入列表框中

汽车 - 价格?

【问题讨论】:

标签: c# arrays listbox


【解决方案1】:

试试这个:

string[,] cars = new string[4, 2] {
    { "VW Golf GTI", "30000" },
    { "Porsche GT3", "300000" },
    { "Porsche Cayenne", "80000" },
    { "BMW M6", "90000" }
};

for (int i = 0; i < cars.GetLength(0); i++)
{
    lstBoxMarket.Items.Add(cars[i, 0] + " - " + cars[i, 1]);
}

您的 cars 版本当前无法编译,因为您正在为数组初始值设定项(2 行 x 2 列)指定常量,但您的数据有 4 行。

【讨论】:

  • 很高兴为您提供帮助!不要忘记回来接受这个作为答案。
【解决方案2】:

更好的方法是将 ItemsSource 绑定到数据模型 Car 类型的新类的 ObservableCollection

你的看法

.xaml

<StackPanel>
        <ListBox ItemsSource="{Binding DataCollection}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Name}" />
                    <TextBlock Text=" - "/>
                    <TextBlock Text="{Binding Id}" />
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
        </ListBox>
</StackPanel>

您的模型 Car.cs

public class Car
{
    public string Name { get; set; }
    public int Id { get; set; }
}

您的视图模型将有一个将绑定到 ItemsSource 的 Collection

CarViewModel.cs

public ObservableCollection<Car> DataCollection { get; set; }

DataCollection = new ObservableCollection<Car> 
{ 
    new Car { Name = "VW Golf GTI", Id = 30000 }, 
    new Car { Name = "Porsche GT3", Id = 30000 }, 
    new Car { Name = "Porsche Cayenne", Id = 80000 }, 
    new Car { Name = "BMW M6", Id = 90000 }
};

【讨论】:

  • +1 以获得很好的答案。但是,通过转换器(或使用 StringFormat)或单一视图模型属性绑定到您的模型的单个 TextBlock 可能会更好,因此最终结果在逻辑上不是三个单独的文本块。例如,三个单独的文本块将被屏幕阅读器读取为三个单独的字符串。
【解决方案3】:

使用DataSource属性加载多维数组的数据。

listBox1.MultiColumn = true;
    listBox1.DataSource = cars;

【讨论】:

    猜你喜欢
    • 2016-12-14
    • 2020-03-23
    • 2018-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多