简体   繁体   中英

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

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

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}}/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM