简体   繁体   中英

c# variable listview items in a ListView

I got a WPF ListView:

<ListView Margin="10,10,0,10" Grid.Row="0" HorizontalContentAlignment="Right" MouseDoubleClick="ListView_MouseDoubleClick" VerticalAlignment="Stretch" Name="listViewConfigItems" MinHeight="300" HorizontalAlignment="Stretch">
//hard coded columns
</ListView>

And I need to add items to this list programmatic and now also variable (read from an xml configuration file)

I used to populate items to the list like this:

 //Populate items to listView
foreach (var obj in objectList)
{
 myWindow.listViewConfigItems.Items.Add(new MyItem
            {
                DisplayName = obj.DisplayName,                   
                Title = obj.Title,
                Description = obj.Description
             });
}

 //....//

 internal class MyItem
    {
        public string DisplayName { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
    }

This works fine, the items are placed on the list and mapped to the right columns. Now my challenge is to NOT hardcode those properties, but be able to make my own in the XML file. I guess this would require that the class MyItem would be dynamic in some way.

I managed to make the columns populate automatic like this (semi-pseudo):

 foreach (var conf in GetColumnConfiguration())
{
        {
           GridViewColumn gvc = new GridViewColumn()
            {
                Header = GetHeaderDisplayName(),
                DisplayMemberBinding = new Binding(GetBindingName())


            };
 }

But I'm not sure how to make a similar approach to add Items on the ListView.

I am using .NET 3.5. The application cannot use .NET 4 or above, but I'm able to install custom assemblies if needed.

Thanks!

您可能想使用XmlDataProvider(只需在Google上进行搜索)并设置AutoGenerateColumns="true"

I resolved it by creating the class at run-time using reflection, inspired by this post: http://mironabramson.com/blog/post/2008/06/Create-you-own-new-Type-and-use-it-on-run-time-(C).aspx

Then I am able to handle variable properties from users.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM