简体   繁体   中英

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

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>

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.

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

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

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