c# - 如何在 XAML 中绑定(bind) ObservableCollection 的属性

标签 c# wpf xaml mvvm

我有一个 ChatroomViewModel:

//ObservableObject implements INotifyPropertyChanged
public class ChatroomViewModel : ObservableObject
{
    private ObservableCollection<Chat> _chatCollection;
    public ObservableCollection<Chat> ChatCollection
    {
        get { return this._chatCollection;  }
        set
        {
            if (null != value)
            {
                this._chatCollection = value;
                OnPropertyChanged("ChatCollection");
            }
        }
    }
}

聊天室 View :

<ListBox Grid.Row="1" ItemsSource="{Binding ChatCollection}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="Name: "/>
                <TextBlock Text="{Binding ChatCollection.Name}"/>
                <TextBlock Text="Created by: "/>
                <TextBlock Text="{Binding ChatCollection.CreatedBy}"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

这是聊天模型:

//ObservableDatabaseModel also implements INotifyPropertyChanged
public class Chat : ObservableDatabaseModel
{
    private string _name;
    public string Name 
    {
        get { return this._name; }
        set
        {
            this._name = value;
            base.OnPropertyChanged("Name");
        }
    }

    private string _createdBy;        
    public string CreatedBy 
    {
        get { return this._createdBy; }
        set
        {
            this._createdBy = value;
            base.OnPropertyChanged("CreatedBy");
        }
    }
}

绑定(bind)有效,但它只显示对象的位置,而不是指定的 Name/Createdby 属性文本。

我不知道为什么这不起作用,我用了 ObservableCollection<Chat>而不是List<Chat>因为它也可以绑定(bind)其属性,所以我还将 INotifyPropertyChanged 实现为“子类”:Chat。

我没有使用任何额外的 MVVM 框架,因此我无法使用 MVVM-light 解决方案或类似的解决方案做太多事情。

最佳答案

DataContext ListBoxItem 内 UI 元素的数量s 已经是您的 Chat 类的实例。

WPF 自动将 ListBoxItemDataContext 及其所有内容分配给 数据项 的相应实例。

因此你的绑定(bind)应该是这样的:

<TextBlock Text="Name: "/>
<TextBlock Text="{Binding Name}"/>
<TextBlock Text="Created by: "/>
<TextBlock Text="{Binding CreatedBy}"/>

关于c# - 如何在 XAML 中绑定(bind) ObservableCollection 的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21528815/

相关文章:

c# 如何 FormWindowState.Normal

wpf - 在样式的 EventTrigger 中触发命令?

Silverlight 3 - 将枚举从 DomainServiceContext 绑定(bind)到组合框

c# - 如何处理检索 i2c 缓冲区和设置模型/实体属性?

c# - 使用正则表达式分隔多部分电子邮件

wpf - 如何在listview的datatemplate中订阅事件

c# - 如何在 PRISM 模块中使用 ReactiveUI

wpf - 验证错误模板未显示数据错误

c# - 为简单的 Person 类实现 iNotifyPropertyChanged 会导致 VisualStudio XAML 设计器崩溃

c# - Mvc ViewBag - 无法将 null 转换为 'bool',因为它是不可为 null 的值类型