【问题标题】:Wpf binding list of custom objects to ListBox [duplicate]Wpf将自定义对象的列表绑定到ListBox [重复]
【发布时间】:2017-09-17 08:07:45
【问题描述】:

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

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

public MainWindow()
{
    InitializeComponent();

    this.users = User.GetAllUsersFromFile();

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

还有 XML:

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

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

【问题讨论】:

  • 使用ObservableCollection&lt;User&gt; users 应该没问题。
  • 列表是动态的还是静态的?
  • 为什么是this.listBox.DataContext = users;?这没有任何目的。十分钟阅读文档可以让您在两天内为随机属性分配任意值。

标签: c# wpf data-binding


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-20
    • 2021-07-02
    • 2011-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-08
    • 1970-01-01
    相关资源
    最近更新 更多