Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在wpf datagrid中itemssource为null时显示空行_C#_Wpf_Mvvm_Wpfdatagrid - Fatal编程技术网

C# 在wpf datagrid中itemssource为null时显示空行

C# 在wpf datagrid中itemssource为null时显示空行,c#,wpf,mvvm,wpfdatagrid,C#,Wpf,Mvvm,Wpfdatagrid,我正在使用mvvm进行wpf中的一个项目。我只想在wpf数据网格上显示一行以添加新项,我有一个ItemsSource,但它是null,并且canUserAddRows设置为true 提前感谢。您需要某种项目资源,即非空。只需初始化您的可观察集合 最简单的方法是通过ViewModel的构造函数执行此操作: public class ViewModel : INotifyPropertyChanged { public ViewModel() { _yourC

我正在使用mvvm进行wpf中的一个项目。我只想在wpf数据网格上显示一行以添加新项,我有一个
ItemsSource
,但它是
null
,并且
canUserAddRows
设置为true


提前感谢。

您需要某种
项目资源
,即
非空
。只需初始化您的
可观察集合

最简单的方法是通过ViewModel的构造函数执行此操作:

public class ViewModel : INotifyPropertyChanged
{
     public ViewModel()
     {
          _yourCollection = new ObservableCollection<yourType>();
          //Now Items can be added, via code behind, or UI !
     }
}
public class ViewModel 
{

     public ObservableCollection<Model> Collection { get; set;}         

     public ViewModel()
     {
          Collection = new ObservableCollection<Model>();
          //Now Items can be added, via code behind, or UI !
     }
}
型号:

public class Model
{
    public string Text { get; set; }
}
Xaml:


结果:

欢迎来到StackOverflow!当你问一个问题时,你应该提供尽可能多的细节。这包括您已经拥有的代码和关于您解决问题的努力/进展的报告。
<DataGrid CanUserAddRows="True"
          AutoGenerateColumns="False"
          IsReadOnly="False"
          ItemsSource="{Binding Collection}">
    <DataGrid.Columns>
        <DataGridTextColumn Width="*" 
                            Header="Value" 
                            Binding="{Binding Text}"/>
    </DataGrid.Columns>
</DataGrid>