我想在我的WPF应用程序中使用MVVM。我目前有一个模型和一个有DataGrid和一些其他控件的视图。我创建了一个基于我的模型的ViewModel,不知道我是否做得正确。该视图只是一个简单的对话框。我想填充DataGrid视图。使用MVVM的WPF对话框
如何告诉DataGrid与ViewModel绑定?
我想绑定属性(像ID和日期之类的viewmodel内)到数据网格。
所以,如果列表中有两个对象我想看到具有特定ID和日期的DataGrid中的两行。
我设置datacontext在类中,而不是xaml。
这是迄今为止代码:
public class ViewModel : INotifyPropertyChanged
{
private string _id;
private DateTime _date;
private ObservableCollection<Object> _list;
public string Id
{
get { return _id; }
set
{
_id = value;
PropertChanged("Id");
}
}
public DateTime Date
{
get { return _date; }
set
{
_date = value;
PropertChanged("Date");
}
}
public ObservableCollection<Object> list
{
get { return _list; }
set
{
_list = value;
PropertChanged("list");
}
}
public LicenseViewModel()
{
list = GetList();
}
public event PropertyChangedEventHandler PropertyChanged;
public void PropertChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
而XAML:
<Window x:Class="Import"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:Controls="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit"
mc:Ignorable="d"
ResizeMode="CanResizeWithGrip"
x:Name="ImportLicense"
d:DesignHeight="493" d:DesignWidth="559"
Title="Import Licenses" SizeToContent="WidthAndHeight">
<Grid Width="538">
<DataGrid x:Name="Imported" VerticalAlignment="Top" AutoGenerateColumns="False" CanUserResizeColumns="True">
<DataGrid.Columns>
<DataGridTextColumn Header="Entitlement ID" Binding="{Binding Path=ID}"/>
<DataGridTextColumn Header="Date Sold" Binding="{Binding Path=Date}"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
我把它用,而不是内部XAML与视图模型上背面itemsources解决。 – alice7 2011-04-29 15:18:42