views:

178

answers:

4

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.

+2  A: 

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.

Mike Hall
i'm really lost here... DataContext? where is that? sorry for being such a noob...
RCIX
DataContext is a property of the control
Rune FS
It's in the cs file, not in the xaml file. It's a member of the base class: System.Windows.FrameworkElement. Just do some searches on WPF data binding and you'll find plenty of help and examples.
Mike Hall
+3  A: 

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

Pavel Minaev
Agreed. This is the basics of data binding in WPF, so the OP really needs to read up about it in general.
Noldorin
I already have an alternate solution but it's hacky (manually adding all required items to the items property of the listbox), and while this is useful it doesn't necessarily get me the solution i need. In this case, i'd like the fish and not the teaching as much...
RCIX
+1  A: 

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.

RCIX
A: 

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}}
Robert Rossney