如何清除 DataGrid 中的特定列?

How do I clear specific columns in DataGrid?

我正在使用 WPF,通过 LinqToSql 连接到 SQL 数据库。 我已经使用 ItemsSource 填充了 DataGrid。

我想清除我的 DataGrid 中的所有内容,除了前两行(ID、名字和名字),当然 Headers,只需按一个按钮。我想(设置为 null 或 0)删除的所有项目都是浮点数,但我找不到正确的逻辑来执行此操作。

这是我的 DataGrid 的图片-->

public partial class Spisak : Microsoft.Office.Interop.Excel.Window
{
    DiplomskiDataContext diplomski = new DiplomskiDataContext();
    public Spisak()
    {
        InitializeComponent();

        dataGridRadnici.ItemsSource = diplomski.Radniks.ToList();
    }
}

这是我后面的代码,这里是Xaml代码:

<DataGrid HorizontalAlignment="Left" Name="dataGridRadnici" AutoGenerateColumns="False" Height="260" Margin="10,120,0,0" VerticalAlignment="Top" Width="550">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Ime" Binding="{Binding Ime}"></DataGridTextColumn>
            <DataGridTextColumn Header="Prezime" Binding="{Binding Prezime}"></DataGridTextColumn>
            <DataGridTextColumn Header="BrSati" Binding="{Binding BrojSati, Converter={StaticResource ThreePlaceConverter}}"></DataGridTextColumn>
            <DataGridTextColumn Header="Prekovremeni" Binding="{Binding BrojPrekovremenih, Converter={StaticResource ThreePlaceConverter}}"></DataGridTextColumn>
            <DataGridTextColumn Header="Gorivo" Binding="{Binding BrojDana, Converter={StaticResource ThreePlaceConverter}}"></DataGridTextColumn>
            <DataGridTextColumn Header="Bonus" Binding="{Binding Bonus}"></DataGridTextColumn>
            <DataGridTextColumn Header="VracanjeDuga" Binding="{Binding VracanjeDuga}"></DataGridTextColumn>
            <DataGridTextColumn Header="UkZarada" Binding="{Binding UkupnaPlata, Converter={StaticResource ThreePlaceConverter}}"></DataGridTextColumn>
            <DataGridTextColumn Header="UkSaGorivom" Binding="{Binding UkupnoSaGorivom, Converter={StaticResource ThreePlaceConverter}}"></DataGridTextColumn>
        </DataGrid.Columns>
        <DataGrid.ContextMenu>
            <ContextMenu>
                <MenuItem Header="Izmeni" Click="MenuItem_Click"></MenuItem>
                <MenuItem Header="Obrisi" Click="MenuItem_Click_1"></MenuItem>
            </ContextMenu>
        </DataGrid.ContextMenu>
    </DataGrid>

将您希望能够清空的列的类型从 float 更改为 Nullable<float> (float?),然后只需将属性设置为 null :

var sourceList = dataGridRadnici.ItemsSource as List<Radnik>; //or whatever your data is called
foreach (var item in sourceList)
{
    item.BrojPrekovremenih = null; // or 0
    //set the other properties the same way...
}

您还需要实现 INotifyPropertyChanged 接口并在数据 class 中引发 property change notifications