将ListBox绑定到静态列表并创建DataTemplate

时间:2012-06-01 19:20:33

标签: c# wpf templates data-binding

我使用静态成员列表创建了以下类:

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中绑定它。我无法使绑定工作,它不会返回值。

<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个成员的数组,但是我没有得到任何绑定到公共属性的结果。

1 个答案:

答案 0 :(得分:2)

如果您像这样重新安排代码,它可以正常工作:

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

您不应该依赖于初始化静态字段的特定顺序。根据{{​​3}},静态字段初始化的顺序是未定义的。

使用静态构造函数可能会使代码更具可读性:

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