Bastien Vandamme
Bastien Vandamme

Reputation: 18485

Adding WPF ListView Items Dynamically

I'm looking for examples or help to create a WPF listview of files.

<ListView Margin="10,10,0,13" Name="ListView1" HorizontalAlignment="Left"
         VerticalAlignment="Top" Width="194" Height="200">

I Load my files with this method :

    private void AddFiles_Click(object sender, RoutedEventArgs e)
    {
        OpenFileDialog ofd = new OpenFileDialog();
        ofd.Multiselect = true;

        if (ofd.ShowDialog() == true)
        {
            string[] filePath = ofd.FileNames;
            string[] safeFilePath = ofd.SafeFileNames;
        }
    }

What should I do now ?

ListView1.Items.Add(...) don't seems to work. In fact I can't find ListView1 from my cs code.

I found info here

Upvotes: 0

Views: 2561

Answers (3)

Sergey K
Sergey K

Reputation: 4114

I would recommend to use DataBinding for display items in ListView you should bind the ObservableColliction files; with your ListView ItemSource property and when you add or remove files in collection on the ListView items will be updated automaticaly

for example look at this article

Upvotes: 2

fixagon
fixagon

Reputation: 5566

as a quick and dirty way you can assign the collection of files directly to the ItemsSource property of the ListView

ListView1.ItemsSource = safeFilePath;

in the XAML you can add an ItemTemplate to customize the visualization of the single files

Upvotes: 1

Henk Holterman
Henk Holterman

Reputation: 273854

Simple,

  • Store your file(name)s in a list (ObservableCollection) in your ViewModel
  • Databind the ListView.ItemSource to that collection
  • Add/Remove/Change files in the Collection, not in the Listview

If you're not using an explicit ViewModel, use your WindowClass as such.

Upvotes: 1

Related Questions