对不起,这可能是一个简单的问题。
我有一个Appointment类,它有各种字符串属性。
我在我的视图模型中有一个可观察的集合,但每当我将任何属性绑定到列表框时,它会返回第一个条目的每个字符,并拥有它自己的行
抱歉,我手边没有代码,但总结一下
сlass Appointment
{
public Appointment(string ыubject)
{
Subject = subject;
}
public string Subject { get; set; }
}
class Appointments
{
public Appointments()
{
ListOfAppointments = new ObservableCollection<Appointment>();
ListOfAppointments.Add(new ListOfAppointments("Example"));
}
public ObservableCollection<Appointment> ListOfAppointments { get; set; }
}
在XAML中:
<ListBox DataContext="{StaticResource AppointementViewModel, Path=ListOfAppointments}" ItemSource="{Binding Subject }" />
希望这是正确的。列表框显示的结果是
E
X
A
M
P
L
E
我现在很少提及,因为我没有在初始提取后更新信息,所以我没有实现INotifyProperty
请注意正确加载数据这只是一个复制的快速示例。
此外,如果我在后端使用linq来查询它,它会返回正确的结果,但是因为实际的实现有多个字段,这将是一个麻烦的解决方法。有什么想法吗?
答案 0 :(得分:4)
ListBox itemsSource应该是ListOfAppointments,在datatemplate中你可以绑定主题属性
<ListBox DataContext="{StaticResource AppointementViewModel}" ItemSource="{Binding ListOfAppointments}" ItemTemplate="{StaticResource MyTemplate}"/>
<DataTemplate x:Key="MyTemplate">
<TextBlock Text="{Binding Subject}" />
</DataTemplate>
在问题中提供的代码示例中,ListOfAppoinments
作为DataContext
的{{1}}和ListBox
作为Subject
。因此ListBox将ListOfAppoinments中的第一个对象的Subject属性作为其ItemsSource。因此,字符串被拆分并分配给每个ItemsSource
。
在上面的代码中,我们将ListBoxItem
作为ListOfAppoinments
。因此,每个ItemsSource
对象都从列表中获取并分配给Appointment
。由于我们已将ListBoxItems
绑定到Subject
中的TextBlock
,因此会显示。