如何禁止Wpf DataGrid单击事件创建一个新行

时间:2017-03-06 09:48:50

标签: c# wpf datagrid

当我使用DataGrid时,因为我需要添加新行来编辑数据,所以,我必须让

CanUserAddRows="True" . 

但我发现,当我点击另一个单元格时,dataGrid将构建一个新的Line,我不知道如何禁止该事件。我发现因为我绑定了“float”或“int”数据,单元格将用“0”填充单元格,我可以做的是让空间没有“0”来填充它。所以任何人都可以给我一些建议,谢谢。enter image description here

1 个答案:

答案 0 :(得分:0)

您应该将DataGridTextColumn的绑定设置为int?类型的属性,而不是int。换句话说,考虑一个模型有两个属性的情况,一个是int类型而另一个是int?:

public class Model : INotifyPropertyChanged
{
    int? _indexNullable;
    public int? IndexNullable { get { return _indexNullable; } set { _indexNullable = value; RaisePropertyChanged("IndexNullable"); } }

    int _index;
    public int Index { get { return _index; } set { _index = value; RaisePropertyChanged("Index"); } }

    public event PropertyChangedEventHandler PropertyChanged;
    internal void RaisePropertyChanged(string propname)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propname));
    }
}

您可以在以下DataGrid中看到差异:

<DataGrid ItemsSource="{Binding Models}" DataContext="{Binding}" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Index}"/>
        <DataGridTextColumn Binding="{Binding IndexNullable}"/>
    </DataGrid.Columns>
</DataGrid>