[英]How to: Fill a ListView by using C# instead of using XAML
How to: Fill a ListView by using C# instead of using XAML 如何:使用C#而不是XAML填充ListView
I would like to fill a ListView
by using C# (WPF), not by using XAML. 我想使用C#(WPF)而不是XAML来填充ListView
。 The reason for this is, that we do not know the number of elements before runtime. 原因是,在运行时之前我们不知道元素的数量。
This is my working XAML code: 这是我的工作XAML代码:
<ListView Name="listView_BusinessContacts" SelectionMode="Single">
<ListViewItem Selected="ListViewItem_Selected">
<DockPanel DockPanel.Dock="Top" Name="dockPanel_1">
<Image DockPanel.Dock="Left" Source="/X;component/Images/folder.png" Stretch="None" />
<Label Content="Test 123" DockPanel.Dock="Right" Name="label_1" />
</DockPanel>
</ListViewItem>
</ListView>
My idea is first to create the ListViewItem
. 我的想法是首先创建ListViewItem
。 After that, I could create the DockPanel
. 之后,我可以创建DockPanel
。 But now, I do not know, how to add two elements to a DockPanel
(here: Image
and Label
). 但是现在,我不知道如何在DockPanel
添加两个元素(此处为Image
和Label
)。 After that, I would add the DockPanel
to the ListViewItem
and than I would add that ListViewItem
to the ListView
. 之后,我将DockPanel
添加到ListViewItem
然后将那个ListViewItem
添加到ListView
。
I hope, that you understand what I want to do. 希望您能理解我的想法。
Solution by SynerCoder: SynerCoder解决方案:
public void SetListViewItems()
{
foreach (var item in File.ReadAllLines(@"C:\Companies\Companies.txt", Encoding.UTF8))
{
Image image = new Image();
image.Source = new BitmapImage(new Uri(@"Images\folder.png", UriKind.Relative));
image.Stretch = Stretch.None;
Label label = new Label();
label.Content = "Test 123";
DockPanel.SetDock(image, Dock.Left);
DockPanel.SetDock(label, Dock.Right);
DockPanel dockPanel = new DockPanel();
dockPanel.Children.Add(image);
dockPanel.Children.Add(label);
ListViewItem listViewItem = new ListViewItem();
listViewItem.Content = dockPanel;
listView_BusinessContacts.Items.Add(listViewItem);
}
}
You can use the following code to create your listview, use the static SetDock
method of the DockPanel
to set the docking positions. 您可以使用以下代码创建列表视图,使用DockPanel
的静态SetDock
方法设置停靠位置。
var listView = new ListView();
foreach (var item in something)
{
var image = new Image();
image.Source = ...;
image.Stretch = Stretch.None;
var label = new Label();
label.Content = "Test 123";
DockPanel.SetDock(image, Dock.Left);
DockPanel.SetDock(label, Dock.Right);
var dockPanel = new DockPanel();
dockPanel.Children.Add(image);
dockPanel.Children.Add(label);
var item = new ListViewItem();
item.Content = dockPanel;
listView.Items.Add(item);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.