我需要允许用户添加直接在DataGrid中的信息,但是将“CanUserAddRows”属性设置为不起作用,只显示如下:
这是我的DataGrid:
<DataGrid x:Name="dtgPersons" Grid.Row="3" CanUserAddRows="True">
<DataGrid.Columns>
<DataGridTextColumn Header="N°" Width="*" />
<DataGridTextColumn Header="Name" Width="*" />
<DataGridTextColumn Header="Carrer" Width="*" />
<DataGridTextColumn Header="Group" Width="*" />
<DataGridTextColumn Header="Age" Width="*" />
</DataGrid.Columns>
</DataGrid>
修改
这是新的网格代码:
<DataGrid x:Name="dtgPerson" Grid.Row="3" ItemsSource="{Binding lstPerson}" AutoGenerateColumns="False" CanUserAddRows="True">
<DataGrid.Columns>
<DataGridTextColumn Header="N°" Width="*" Binding="{Binding No}" />
<DataGridTextColumn Header="Name" Width="*" Binding="{Binding Name}" />
<DataGridTextColumn Header="Carrer" Width="*" Binding="{Binding Carrer}" />
<DataGridTextColumn Header="Group" Width="*" Binding="{Binding Group}" />
<DataGridTextColumn Header="Age" Width="*" Binding="{Binding Age}" />
</DataGrid.Columns>
</DataGrid>
这是我背后的代码: 我的ObservableCollection:
public ObservableCollection<Person> lstPerson { get; set; }
我的主窗口
public MainWindow()
{
InitializeComponent();
DataContext = this;
lstPerson = new ObservableCollection<Person>();
}
我的人类
public class Person
{
public int No { get; set; }
public string Name { get; set; }
public string Carrer { get; set; }
public string Group { get; set; }
public int Age { get; set; }
}
答案 0 :(得分:3)
1)更改网格xaml
<DataGrid ItemsSource="{Binding GridCollection}"
CanUserAddRows="True"
AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="N°" Binding="{Binding Number}" Width="*" />
<DataGridTextColumn Header="Name" Binding="{Binding Name}" Width="*" />
<DataGridTextColumn Header="Carrer" Binding="{Binding Career}" Width="*" />
<DataGridTextColumn Header="Group" Binding="{Binding Group}" Width="*" />
<DataGridTextColumn Header="Age" Binding="{Binding Age}" Width="*" />
</DataGrid.Columns>
</DataGrid>
2)在ViewModel或CodeBehind
中定义您的集合public ObservableCollection<gridDataModel> GridCollection { get; set; }
3)使用前初始化
public MainWindow()
{
InitializeComponent();
DataContext = this;
GridCollection = new ObservableCollection<gridDataModel>();
}
答案 1 :(得分:-1)
您必须定义ItemsSource。
在你的代码背后:
List<YourObj> list = new List<YourObj>();
dtgPersons.ItemsSource = list;