[英]List in Resource.XAML and access in ViewModel
如何在 resources.xaml 中创建一个列表(我将使用它作为我的列表框的 itemsource)以及如何在 ViewModel 中访问它? 谢谢
这可能会有所帮助: Silverlight:在 XAML 中声明数据集合?
然后,您可以使用声明集合的控件的 Resources 属性来访问它。
编辑例如:
你需要声明一个新的集合类型,因为你不能在 XAML 中声明一个泛型类型:
using System.Collections.Generic;
namespace YourNamepace
{
public class Genders : List<string>
{
}
}
然后,在添加必要的命名空间之后,在 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>
您当然可以在内部使用更复杂的数据结构来声明它。 然后,将其用作您的 ListBox 的 ItemsSource:
<ListBox ItemsSource="{Binding Source={StaticResource AvailableGenders}}"/>
那行得通,我刚刚测试过:-)
添加到@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.