RCIX
RCIX

Reputation: 39427

Data Bind a WPF Listbox?

How do i databind a listbox to a List that i have in the containing window's class file? I looked and there's an ItemsSource property that i can set but i'm not sure if this is what i want, nor am i sure what to set it to.

Upvotes: 1

Views: 1489

Answers (4)

Robert Rossney
Robert Rossney

Reputation: 96702

Here are some more ways to do this:

One is to make the list a static property of the window class and then bind to it like this:

{Binding Source={x:Static local:MyWindow.MyList}}

You'd generally only do that if you wanted all instances of the window to use the same list, of course.

Another is to add the list to the window's Resources collection, by putting

Resources.Add("MyListKey", MyList);

in the constructor, before the call to InitializeComponent. (The key has to be in the resource dictionary before the StaticResource markup extension gets executed.) Then you can bind to it like this:

{Binding Source={StaticResource MyListKey}}

Upvotes: 0

RCIX
RCIX

Reputation: 39427

I figured it out: According to this cheatsheet, i needed to use the following:

ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=Categories}"

where Path is set to the name of the Property that contains the list of strings you want to bind against.

Upvotes: 3

Pavel Minaev
Pavel Minaev

Reputation: 101555

It is a very broad question. Your best bet would be to read the introductory topic on MSDN.

Upvotes: 3

Mike Hall
Mike Hall

Reputation: 1151

That's pretty much it:

<ListBox ItemsSource="{Binding}">
</ListBox>

Then set your DataContext to some sort of collection of strings and that's it. If you don't want to bind directly to the DataContext you can do that, but you may want to put this into its own control to better separate functionality anyway.

Upvotes: 3

Related Questions