【发布时间】:2017-10-29 11:50:10
【问题描述】:
我知道这类问题已经被问过很多次了。但我试图在不使用 InotifyProperty 或其他任何东西的情况下实现这一目标。我只想要简单的代码来显示模型中的数据。 为此,我正在尝试使用以下方法绑定 Datagrid。 我有一个模型:
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; }
}
}
一个视图模型:
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 以通过 ViewModel 显示基本 ID 和用户名?
【问题讨论】:
标签: wpf mvvm datagrid viewmodel