Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Wpf将自定义对象列表绑定到ListBox_C#_Wpf_Data Binding - Fatal编程技术网

C# Wpf将自定义对象列表绑定到ListBox

C# Wpf将自定义对象列表绑定到ListBox,c#,wpf,data-binding,C#,Wpf,Data Binding,您好,我想将自定义对象列表绑定到WPF中的列表框。 我有下一个代码: private List<User> users = new List<User>(); public MainWindow() { InitializeComponent(); this.users = User.GetAllUsersFromFile(); this.listBox.DataContext = users; this.listBox.ItemsS

您好,我想将自定义对象列表绑定到WPF中的列表框。 我有下一个代码:

private List<User> users = new List<User>();

public MainWindow()
{
    InitializeComponent();

    this.users = User.GetAllUsersFromFile();

    this.listBox.DataContext = users;
    this.listBox.ItemsSource = users;
}

初始列表按预期显示,但如果列表中添加(或删除)了新项目,则列表不会更新。

正如Sinatr指出的那样,我使用了ObservableCollection,它按预期工作。
谢谢。

使用
ObservableCollection用户
你应该会没事的。列表是动态的还是静态的?为什么
this.listBox.DataContext=users?那没有任何用处。十分钟的阅读文档可以让您在为随机属性指定任意值的两天内完成更多工作。
<ListBox x:Name="listBox" ItemsSource="{Binding}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Name}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>    
</ListBox>
private string name;
private byte[] avatar;

public string Name
{
    get
    {
        return this.name;
    }
    set
    {
        if (value.Any(c => c == ' '))
            throw new Exception("Invalid name. (It cannot contain spaces)");

        this.name = value;
    }
}

public byte[] Avatar
{
    get
    {
        return this.avatar;
    }
    set
    {
        this.avatar = value;
    }
}