将ListBox绑定到静态列表并创建DataTemplate [英] Binding a ListBox to a static list and creating a DataTemplate
问题描述
我创建了一个静态成员列表的类:
I created the following class with a static list of members:
public class Role
{
public static List<Role> AllRoles = new List<Role>()
{
Administrators,
PowerUsers,
Limited
};
public static Role Administrators = new Role() { Name = "Bob" };
public static Role PowerUsers = new Role() { Name = "Jimbo" };
public static Role Limited = new Role() { Name = "Jack" };
public string Name { get; set; }
}
现在我试图在ListBox中绑定一个项目基于每个模板的属性。我不能让绑定工作,它不返回值。
Now I'm trying to bind to it in a ListBox with an item template based on the properties of each. I cannot get the binding to work, it doesn't return the values.
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WPFTests">
<Grid>
<ListBox Width="200" Height="200"
ItemsSource="{Binding Source={x:Static local:Role.AllRoles}}">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding Path=Name}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>
我一定是缺少一些简单的东西。我得到3个复选框来表示一个3个成员的数组,但是我没有得到任何绑定到公共属性的结果。
I must be missing something simple. I am getting 3 checkboxes to represent an array of 3 members, but I'm not getting any results for binding to public properties.
推荐答案
p>如果你重新排列这样的代码,它可以正常工作:
If you rearrange your code like this, it works:
public class Role
{
public static List<Role> AllRoles = new List<Role>()
{
Administrators,
PowerUsers,
Limited
};
public static Role Administrators = new Role() { Name = "Bob" };
public static Role PowerUsers = new Role() { Name = "Jimbo" };
public static Role Limited = new Role() { Name = "Jack" };
public string Name { get; set; }
}
您不应该依赖静态字段初始化的特定顺序。根据 http://msdn.microsoft.com/ en-us / library / aa645758(v = vs.71).aspx ,静态字段初始化的顺序是未定义的。
You should not rely on a specific order in which the static fields are initialized. According to http://msdn.microsoft.com/en-us/library/aa645758(v=vs.71).aspx, the order of static field initialization is undefined.
可能代码将是更可读的静态构造函数:
Probably the code would be more readable with a static constructor:
public class Role
{
public static Role Administrators;
public static Role PowerUsers;
public static Role Limited;
public static List<Role> AllRoles;
static Role()
{
Administrators = new Role() {Name = "Bob"};
PowerUsers = new Role() {Name = "Jimbo"};
Limited = new Role() {Name = "Jack"};
AllRoles = new List<Role>()
{
Administrators,
PowerUsers,
Limited
};
}
public string Name { get; set; }
}
这篇关于将ListBox绑定到静态列表并创建DataTemplate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!