7

Possible Duplicate:
WPF ListView - how to add items programmatically?

How it can be done in C#?

0

6 Answers 6

6

This is how you would add a ListViewItem created in code to your ListView:

myListView.Items.Add(new ListViewItem { Content = "This is an item added programmatically." });

However, I agree with MrTelly that this shouldn't be necessary, you should be setting ListView.ItemsSource to some collection rather than manipulating ListView.Items directly.

If you give us more details about what you want to accomplish maybe we can help you do it the WPF way, which is not always the easy way at first, but it's much easier in the long run.

4

I asked the exact same question HERE (and answered myself - I had a problem in my code). Hope it helps.

4

Adding it directly to the ListView in your App isn't necessarily the "WPF-way". Consider this:

public class BindableListViewModel 
{

     public IList<TypeOfObjectToDisplay> AllObjectsToDisplay;
     public ICommand AddNewItemToList;

     public BindableListViewModel()
     { 
       AllObjectsToDisplay = new ObservableList<TypeOfObjectToDisplay>();
       AddNewItemToList = new RelayCommand(AddNewItem(), CanAddNewItem());
     }

     public bool CanAddNewItem()
     {
       //logic that determines IF you are allowed to add
       //For now, i'll just say that we can alway add.
        return true;
     }

     public void AddNewItem()
     {
       AllObjectsToDisplay.Add(new TypeOfObjectToDisplay());
     }

}

Then, in XAML all that we need to do is bind the ItemsSource of our ListView to our AllObjectsToDisplay list. This allows us to separate the dependency of adding objects directly to our ListView; we can us WPF's strength of Data Binding to remove the direct dependency on HOW we add businesss objects to our UI container we display them in -- a very useful practice!

2

(sorry, can't make comments yet)

As MrTelly is on to...

Bind the listview to a ObservableCollection

ObservableCollection<MyClassItem> lvList = new ObservableCollection<MyClassItem>();
myListview.ItemSource = lvList;

// Add an item
lvList.Add(new MyClassItem("firstname", "lastname"));

That way it will automatically update the UI when changes are made to the collection.

1

If you're using the ListView as it is intended it will be bound to an underlying list of some kind of Object, and that class should implement INotifyChanged. In WPF you don't directly add/remove items from the ListView, you deal with the bound list structure, and it notifies the UI of the change, which then cleverly redraws itself with the new items.

0

You can add columns dynamically to a ListView by using Attached Properties. Check out this article on the CodeProject it explains exactly that...

WPF DynamicListView - Binding to a DataMatrix