【发布时间】:2016-08-05 14:20:54
【问题描述】:
我是 MVVM 新手,我正在尝试将 ObservableCollection 绑定到 Listview。
视图模型
namespace Multiwindow.Viewmodel
{
public class ViewModelBase
{
public Commandclass Cclass { get; set; }
private ObservableCollection<Person> observableprsn = new ObservableCollection<Person>();
public ViewModelBase()
{
Cclass = new Commandclass(this);
}
public void oncommand()
{
for (int i = 0; i < 5; i++)
{
Person p = new Person();
p.Name = "name";
p.Lastname = "lastname" + i;
observableprsn.Add(p);
}
}
}
}
查看
<Window.Resources>
<m:Person x:Key="personmodel"/>
<vm:ViewModelBase x:Key="vmodel"/>
</Window.Resources>
<Grid Background="Gray" DataContext="{StaticResource vmodel}">
<Button Content="Load Window 2" Margin="155,108,177,157"
Command="{Binding Cclass, Source={StaticResource vmodel}}" />
<ListView HorizontalAlignment="Left" Height="100" Width="184"
DataContext="{Binding Source={StaticResource vmodel}}"
ItemsSource="{Binding }">
<ListView.View>
<GridView>
<GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/>
<GridViewColumn Header="Address" DisplayMemberBinding="{Binding Lastname}"/>
</GridView>
</ListView.View>
</ListView>
</Grid>
单击按钮时,我将绑定到列表查看具有属性名称和姓氏的类人循环中的一些数据,我错在哪里。谢谢
【问题讨论】:
-
为什么
ItemsSource="{Binding }">应该是observableprsn是空的 -
您的应用程序中是否有任何绑定错误,请查看绑定错误的输出
-
没有错误,我试过 ItemsSource="{Binding observableprsn }"> 但没有影响。
-
Vm中的命令是否被调用 -
是的 oncommand 被调用。从 ICommand 界面