Search code examples
listxamlviewmodelapplication-resource

List in Resource.XAML and access in ViewModel


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


Solution

  • 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 :-)