Mittens
Mittens

Reputation: 35

Add Items to Columns in a WPF ListView in Code

My question is for WPF (not win forms) and is very similar to this: Add Items to Columns in a WPF ListView

However, I have legacy problems as I have to use a struct which contains about a 100 variables. The struct is required to be passed into a function which will update its values.

struct alotofthings
{
float item1;
float item2;
.
.
.
UInt16 item100;
}

I use System.Reflections to extract out the fieldinfo.name and GetValue() to get the values of the variables. Next I want to display them in a ListView (created at runtime) like

Variable name | Value (<--- This are the column headers)

item1 .............. | 1223.3

item2 ..... ........ | 6.673

... .....................| ...

item100 ...........| 1

The values will dynamically change every few milliseconds as the struct object is updated using a system pipe subscription. I thought of clearing the ListView and repopulating the graph every time this happens (Method 1). But I need help with adding the items to their respective columns.

I also thought of creating a class with INotifyPropertyChanged (Method 2), but this will become the same situation as method 1 as I still have to update the class using the updated struct. I also do not know how to set the binding dynamically as my class would have 100 properties.

Finally I did thought of using ObservableCollection, but then I also will have to clear its contents and re-add items again as the struct gets updated via the legacy updating function (Method 3). I don't know how fast this is compared to method 1.

Upvotes: 0

Views: 5014

Answers (1)

Shahid Neermunda
Shahid Neermunda

Reputation: 1367

Try This Method

      <ListView x:Name="lstvItemsList">
      <ListView.View>
         <GridView>
            <GridViewColumn Header="Id" DisplayMemberBinding="{Binding itemName}"/>
             <GridViewColumn Header="Name" DisplayMemberBinding="{Binding value}"/>
         </GridView>
      </ListView.View>
     </ListView>

Then create a structure for hold values

    public struct Items
    {
        public string itemName { get; set; }
        public string value { get; set; }
    }

Then bind values like this

       lstvItemsList.Items.Add(new Items
                            {
                                itemName ="item1" ,
                                value = "125"
                            }

Upvotes: 2

Related Questions