how to create a list in resources.xaml ( I will use it as itemsource for my listbox) and how can I access it in ViewModel? Thanks
Asked
Active
Viewed 1,666 times
0
-
1The ViewModel getting stuff from the view does not sound very clean to me. – Johan Larsson Apr 23 '13 at 08:33
-
@JohanLarsson Yups I know it's kinda inappropriate, but according to my boss I should separate UI related stuff, that's why I will create a list in resources instead of ViewModel. I'm actually having a hard time to implement this. My real goal is to create three static items in a list i.e(name,age,gender) then when I click the item I should navigate to their respective page. Can you help me on this? Thanks! – JennyJane Apr 23 '13 at 09:04
-
Maybe add the lists to app.config and create properties in the ViewModel that resolves the data from app.config. Then bind the view to those properties? Maybe [this](http://stackoverflow.com/questions/1779117/how-to-get-a-liststring-collection-of-values-from-app-config-in-wpf) is helpful. – Johan Larsson Apr 23 '13 at 09:50
2 Answers
1
This might help : Silverlight: Declaring a collection of data in XAML?
You can then access it by using the Resources property of the control you declare the collection in.
EDIT For example:
You need to declare a new collection type as you can't declare a generic type in XAML:
using System.Collections.Generic;
namespace YourNamepace
{
public class Genders : List<string>
{
}
}
Then you declare a list in XAML, after adding the necessary namespaces:
xmlns:local="clr-namespace:YourNamespace"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
...
<Window.Resources>
<local:Genders x:Key="AvailableGenders">
<sys:String>Female</sys:String>
<sys:String>Male</sys:String>
</local:Genders>
</Window.Resources>
You can of course declare it with more complex data structures inside. Then, use that as your ListBox's ItemsSource:
<ListBox ItemsSource="{Binding Source={StaticResource AvailableGenders}}"/>
That works, I've tested it just now :-)

Community
- 1
- 1

Jeremy Gilbert
- 361
- 3
- 9
-
Thanks for that. Do you know if the items from the list can be used as item source for my listbox? I mean the one created in XAML? – JennyJane Apr 23 '13 at 09:35
-
Sure, you can use something like `ItemsSource={Binding Source={StaticResource YourCollectionKey}}` – Jeremy Gilbert Apr 23 '13 at 12:04
-
I cannot create a list using XAML for some reason, would you mind to show me some example aside from the sample found at the link you have provided? Thanks much for you help. – JennyJane Apr 25 '13 at 01:42
-
0
Adding to @JerimyGilbert answer, you can populate the list from the class and use it directly from XAML like so:
using System.Collections.Generic;
namespace YourNamepace
{
public class Genders : List<string>
{
public Genders()
{
Add("Male");
Add("Female");
}
}
}
<Window.Resources>
<local:Genders x:Key="Genders"/>
</Window.Resources>
<ListBox ItemsSource={Binding Source={StaticReource Genders}}/>

Redfreestyle
- 1
- 1