C# 如何在XAML中绑定ObservableCollection的属性
我有一个聊天室视图模型:C# 如何在XAML中绑定ObservableCollection的属性,c#,wpf,xaml,mvvm,C#,Wpf,Xaml,Mvvm,我有一个聊天室视图模型: //ObservableObject implements INotifyPropertyChanged public class ChatroomViewModel : ObservableObject { private ObservableCollection<Chat> _chatCollection; public ObservableCollection<Chat> ChatCollection {
//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");
}
}
}
}
绑定可以工作,但它只显示对象的位置,而不是指定的名称/Createdby属性文本
我不知道为什么这不起作用,我使用了ObservableCollection
而不是List
,因为它也可以绑定它的属性,我还实现了InotifyProperty更改为“子类”:Chat
我没有使用任何额外的MVVM框架,因此我无法使用MVVM轻型解决方案或类似的解决方案。s中的UI元素已经是您的聊天类的一个实例
WPF自动将ListBoxItem
的DataContext
及其所有内容分配给数据项的相应实例
因此,您的绑定应该如下所示:
<TextBlock Text="Name: "/>
<TextBlock Text="{Binding Name}"/>
<TextBlock Text="Created by: "/>
<TextBlock Text="{Binding CreatedBy}"/>
数据模板中的数据上下文是一个项目
试试这个:
<ListBox Grid.Row="1" ItemsSource="{Binding ChatCollection}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="Name: "/>
<TextBlock Text="{Binding Name}"/>
<TextBlock Text="Created by: "/>
<TextBlock Text="{Binding CreatedBy}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</List
<TextBlock Text="Name: "/>
<TextBlock Text="{Binding Name}"/>
<TextBlock Text="Created by: "/>
<TextBlock Text="{Binding CreatedBy}"/>
<ListBox Grid.Row="1" ItemsSource="{Binding ChatCollection}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="Name: "/>
<TextBlock Text="{Binding Name}"/>
<TextBlock Text="Created by: "/>
<TextBlock Text="{Binding CreatedBy}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</List