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.
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.
It is a very broad question. Your best bet would be to read the introductory topic on MSDN.
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.
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}}