我是WPF和MVVM的新手。我试图在我的项目中使用Datagrid和Collectionviewsource。我已经达到了以下某个级别,但我的Datagrid没有显示任何行。下面是代码部分。我想弄清楚我在这里缺少什么。请注意,我只发布此问题所必需的代码部分。
ScanBatchWindow.xaml.cs
public partial class ScanBatchWindow : Window
{
public ScanBatchWindow()
{
InitializeComponent();
ScanBatchViewModel pMV = new ScanBatchViewModel();
this.DataContext = pMV;
}
}
ScanBatchWindow.xaml
<Window x:Class="BatchManPOC.ScanBatchWindow"
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:BatchManPOC"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:cmdBehavior="clr-namespace:BatchManPOC.CmdBehavior"
xmlns:video="clr-namespace:BatchManPOC.Video"
xmlns:Custom="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
mc:Ignorable="d"
Title="ScanBatchWindow"
Height="800"
Width="800">
<Window.Resources>
<CollectionViewSource Source="{Binding p_ListBatches}" x:Key="CVS"/>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
</Grid.RowDefinitions>
<Custom:DataGrid ItemsSource="{Binding Source={StaticResource CVS}}" Margin="8" Grid.Row="0" AutoGenerateColumns="True" IsReadOnly="True">
</Custom:DataGrid>
</Grid>
</Window>
ScanBatchViewModel.cs
请注意,我有 BaseViewModel ,它继承自 INotifyPropertyChanged 。
public class ScanBatchViewModel : BaseViewModel
{
public CollectionViewSource CVS { get; set; }
public ObservableCollection<Batch> p_ListBatches { get; set; }
public class Batch
{
public DateTime p_dCreated;
public int p_iReference;
public BatchStatus p_iBatchStatus;
public string p_sFromBranch;
}
/// <summary>
/// Initializes a new instance of the ScanBatchViewModel class.
/// </summary>
public ScanBatchViewModel()
{
LoadBatches();
CVS = new CollectionViewSource();
}
public void LoadBatches()
{
//Add sample objects
p_ListBatches.Add(new Batch() { p_dCreated = DateTime.Now, p_iBatchStatus = BatchStatus.DOC_STATUS_CREATED, p_iReference = 1, p_sFromBranch = "7010888" });
p_ListBatches.Add(new Batch() { p_dCreated = DateTime.Now, p_iBatchStatus = BatchStatus.DOC_STATUS_DELETED, p_iReference = 2, p_sFromBranch = "7010999" });
p_ListBatches.Add(new Batch() { p_dCreated = DateTime.Now, p_iBatchStatus = BatchStatus.DOC_STATUS_RECEIVED, p_iReference = 3, p_sFromBranch = "7010000" });
p_ListBatches.Add(new Batch() { p_dCreated = DateTime.Now, p_iBatchStatus = BatchStatus.DOC_STATUS_SENT, p_iReference = 4, p_sFromBranch = "7010777" });
}
}