Search code examples
c#xamllistviewadditiondockpanel

How to: Fill a ListView by using C# instead of using XAML


How to: Fill a ListView by using C# instead of using XAML

I would like to fill a ListView by using C# (WPF), not by using XAML. The reason for this is, that we do not know the number of elements before runtime.

This is my working XAML code:

<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. After that, I could create the DockPanel. But now, I do not know, how to add two elements to a DockPanel (here: Image and Label). After that, I would add the DockPanel to the ListViewItem and than I would add that ListViewItem to the ListView.

I hope, that you understand what I want to do.

Solution by 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);
        }
    }

Solution

  • You can use the following code to create your listview, use the static SetDock method of the DockPanel to set the docking positions.

    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);
    }