Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding ListBox to List (Collection) in XAML

I'm learning WPF, so I'm kind of n00b in this. I saw some examples about how to do what I want to do, but nothing exactly...

The question: I want to bind List to ListBox. I want to do it in XAML, w/o coding in code behind. How can I achieve that?

Right now I do it that way:

XAML

<ListBox x:Name="FileList">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Label Content="{Binding Path=.}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Code behind

public MainWindow()
{
    // ...
    files = new List<string>();
    FileList.ItemsSource = files;
}

private void FolderBrowser_TextChanged(object sender, RoutedEventArgs e)
{
    string folder = FolderBrowser.Text;
    files.Clear();
    files.AddRange(Directory.GetFiles(folder, "*.txt", SearchOption.AllDirectories));
    FileList.Items.Refresh();
}

But I want to get rid of FileList.ItemsSource = files; and FileList.Items.Refresh(); in C# code.

Thanks

like image 255
David Avatar asked Apr 20 '10 20:04

David


1 Answers

First, setup the binding in your listbox:

<ListBox x:Name="FileList" ItemsSource="{Binding Files}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Label Content="{Binding Path=.}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

or

<ListBox x:Name="FileList" ItemsSource="{Binding Files}" DisplayMemberPath="."/>

Next, make sure "Files" is a property in your DataContext (or code behind). (You can't bind to fields, only properties...)

Ideally, you'll want to make Files an ObservableCollection<T> instead of a List<T>, as well. This will allow the binding to handle adding or removing elements correctly.

If you do these two things, it should just work correctly.

like image 72
Reed Copsey Avatar answered Sep 19 '22 12:09

Reed Copsey