【问题标题】:Windows Presentation Foundation How to add items to Listview using codeWindows Presentation Foundation 如何使用代码将项目添加到 Listview
【发布时间】:2020-01-14 23:52:48
【问题描述】:

我想将项目添加到我使用 C# 动态创建的列表视图中。 它看起来有点像这样:

System.Windows.Controls.ListView test = new ListView();
test.Margin = new Thickness(28 + i, 23,485 - i, 23);
test.BorderBrush = new SolidColorBrush(Colors.Red);
test.BorderThickness = new Thickness(2);
test.VerticalContentAlignment = VerticalAlignment.Center;
Grid.SetColumn(test,1);
Grid.SetRow(test,1);

现在显然我创建的列表视图完全是空的。

我的问题又来了:是否可以添加项目(比如从一个对象)并在我在这里创建的那些 Listview 中显示它们?

【问题讨论】:

标签: c# wpf xaml listview dynamically-generated


【解决方案1】:

问题:是否可以添加项目(比如从一个对象)并在我在这里创建的列表视图中显示它们?

假设你从一个对象中得到一个字符串列表。比如,objectMain.stringlist,其中objectMain 是您的对象,stringlist 是您对象内部的一个属性 (List<string>)。然后,您可以将其分配为 test.ItemsSource = objectMain.stringlist

不推荐使用后面的代码。尝试使用 MVVM 并从 xaml 创建 UIElements。

【讨论】:

    【解决方案2】:

    我建议您使用 MVVM 模式将列表绑定到 ListView 中的 ItemsSource 并在 xaml 中执行此操作,但在代码中仍然可以手动使用。

    GridView gv = new GridView();
    gv.Columns.Add(new GridViewColumn() { Header = "Something" });
    test.View = gv;
    test.Items.Add("Data1");
    

    【讨论】:

      猜你喜欢
      • 2014-04-13
      • 1970-01-01
      • 2012-10-17
      • 2011-10-04
      • 2017-08-10
      • 1970-01-01
      • 2016-03-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多