我有一个 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 自动将 ListBoxItem
的 DataContext
及其所有内容分配给 数据项 的相应实例。
因此你的绑定(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/