Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF/C# Binding custom object list data to a ListBox?

Tags:

I've ran into a bit of a wall with being able to bind data of my custom object list to a ListBox in WPF.

This is the custom object:

public class FileItem {     public string Name { get; set; }     public string Path { get; set; } } 

And this is the list:

private List<FileItem> folder = new List<FileItem>(); public List<FileItem> Folder { get { return folder; } } 

The list gets populated and maintained by a FileSystemWatcher as files get moved around, deleted, renamed, etc. All the list does is keeps tracks of names and paths.

Here's what I have in the MainWindow code-behind file (it's hard coded for testing purposes for now):

FolderWatcher folder1 = new FolderWatcher(); folder1.Run(@"E:\MyApp\test", "*.txt");  listboxFolder1.ItemsSource = folder1.Folder; 

Here's my XAML portion:

<ListBox x:Name="listboxFolder1" Grid.Row="1" BorderThickness="0"           ItemsSource="{Binding}"/> 

Unfortunately, the only thing that gets displayed is MyApp.FileItem for every entry. How do I display the specific property such as name?

like image 604
B.K. Avatar asked Sep 09 '13 06:09

B.K.


People also ask

Is WPF and C# same?

C# is a programming language. WPF is a technology used to develop rich GUI applications using C# (or any other . NET language).

Is WPF still relevant 2022?

“WPF would be dead in 2022 because Microsoft doesn't need to be promoting non-mobile and non-cloud technology. But WPF might be alive in that sense if it's the best solution for fulfilling specific customer needs today. Therefore, having a hefty desktop application needs to run on Windows 7 PCs with IE 8.

Is WPF discontinued?

It was in 2006 that Windows Presentation Foundation (WPF) was released with . NET framework 3.0. Over the years it got improved and it is still now in the market in 2021.

What is WPF in C#?

Windows Presentation Foundation is a UI framework that creates desktop client applications. The WPF development platform supports a broad set of application development features, including an application model, resources, controls, graphics, layout, data binding, documents, and security.


1 Answers

You will need to define the ItemTemplate for your ListBox

    <ListBox x:Name="listboxFolder1" Grid.Row="1" BorderThickness="0"       ItemsSource="{Binding}">        <ListBox.ItemTemplate>          <DataTemplate>            <TextBlock Text="{Binding Name}"/>          </DataTemplate>        </ListBox.ItemTemplate>      </ListBox> 
like image 109
Nitin Avatar answered Oct 05 '22 12:10

Nitin