Add ListViewItem programmatically to Listview in WPF

Possible duplicate:
WPF ListView - how to add objects programmatically?

How to do it in C #?

+5
source share
6 answers

Here's how you would add the ListViewItemcode you created to yours ListView:

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

However, I agree with MrTelly that this is not necessary, you should install ListView.ItemsSourcein some collection, and not directly manipulate ListView.Items.

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

+6

( - ). , .

+4

ListView "WPF-". :

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

}

XAML , , ItemsSource ListView AllObjectsToDisplay. ListView; WPF , , , - !

+4

(, )

MrTelly ...

ObservableCollection

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

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

, , .

+2

ListView, , - , INotifyChanged. WPF / ListView, , .

+1

Dynamic columns can be added to the ListView using Attached Properties. Check out this article in CodeProject , it explains exactly what ...

WPF DynamicListView - binding to DataMatrix

0
source

All Articles