简体   繁体   English

Resource.XAML 中的列表和 ViewModel 中的访问

[英]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?如何在 resources.xaml 中创建一个列表(我将使用它作为我的列表框的 itemsource)以及如何在 ViewModel 中访问它? Thanks谢谢

This might help : Silverlight: Declaring a collection of data in XAML?这可能会有所帮助: Silverlight:在 XAML 中声明数据集合?

You can then access it by using the Resources property of the control you declare the collection in.然后,您可以使用声明集合的控件的 Resources 属性来访问它。

EDIT For example:编辑例如:

You need to declare a new collection type as you can't declare a generic type in XAML:你需要声明一个新的集合类型,因为你不能在 XAML 中声明一个泛型类型:

using System.Collections.Generic;

namespace YourNamepace
{
    public class Genders : List<string>
    {
    }
}

Then you declare a list in XAML, after adding the necessary namespaces:然后,在添加必要的命名空间之后,在 XAML 中声明一个列表:

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:

<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:添加到@JerimyGilbert 答案,您可以从类中填充列表并直接从 XAML 中使用它,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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