我知道这种类型的问题已经问了很多次。但我试图在不使用InotifyProperty或其他任何东西的情况下实现此目的。我只是想要显示来自模型的数据的简单代码。 为此,我尝试使用以下方法绑定Datagrid。 我有一个模型:使用MVVm绑定DataGrid使用WPF
public class PrimaryModel
{
private int _id;
public int ID
{
get { return _id; }
set { _id = value; }
}
private string _userName;
public string UserName
{
get { return _userName; }
set { _userName = value; }
}
private string _password;
public string Password
{
get { return _password; }
set { _password = value; }
}
private DateTime _createdDateTime;
public DateTime CreatedDateTime
{
get { return _createdDateTime; }
set { _createdDateTime = value; }
}
private DateTime _lastLoginDateTime;
public DateTime LastLoginDateTime
{
get { return _lastLoginDateTime; }
set { _lastLoginDateTime = value; }
}
private bool _isActive;
public bool IsActive
{
get { return _isActive; }
set { _isActive = value; }
}
}
一个ViewModel:
public class PrimaryViewModel
{
private ObservableCollection<PrimaryModel> _UsersList;
public PrimaryViewModel()
{
_UsersList = new ObservableCollection<PrimaryModel>
{
new PrimaryModel { ID=1,UserName="Raghava",Password="Something",CreatedDateTime=DateTime.Now,LastLoginDateTime=DateTime.Now,IsActive=true }
};
}
public ObservableCollection<PrimaryModel> Users
{
get { return _UsersList; }
set { _UsersList = value; }
}
}
而XAML文件:
<Window x:Class="Sample4.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Sample4"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<DataGrid Name="usersData" ItemsSource="{Binding Source=_UsersList}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Path=ID}" />
<DataGridTextColumn Binding="{Binding Path=UserName}" />
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
如何绑定DataGrid中通过视图模型来显示基本ID和用户名?
做对这个问题没有多少了解。所以,基本上,我只是试图用一些数据填充数据网格。我尝试根据您的建议更新我的代码,但我仍然无法查看输出。 – raghava
就像我在我的答案中所写的那样:您还需要设置View的DataContext。你做到了吗? –
什么MightyBadaboom说...转到MainWindow.xaml.cs - 然后到构造函数public MainWindow() { InitializeComponent(); this.DataContext = new PrimaryViewModel(); }' – Peter