简体   繁体   English

c#Wpf数据网格

[英]c# Wpf Data grid

Is it possible to update rows and display them again, I came across a problem because if I add immediately 3 items to the table then they display everything is ok but when I later add an element to the array and is displayed in the grid, the next element is not added 是否可以更新行并再次显示它们,我遇到了一个问题,因为如果我立即将3个项目添加到表中,则它们显示的一切正常,但是当我以后将元素添加到数组并显示在网格中时,未添加下一个元素

public partial class MainWindow : Window
{
    public DateTime start;

    public DateTime end;

    public List<Action> zadania = new List<Action>();

    public MainWindow()
    {
        InitializeComponent();
        var urlop = new Action(); 
    }
     private void DatePicker_SelectedDateChanged(object sender,
        SelectionChangedEventArgs e)
    {
        // ... Get DatePicker reference.
        var picker = sender as DatePicker;

        // ... Get nullable DateTime from SelectedDate.
        DateTime? date = picker.SelectedDate;
        if (date == null)
        {
            // ... A null object.
            this.Title = "No date";
        }
        else
        {
            // ... No need to display the time.
            this.Title = date.Value.ToShortDateString();
            start = date.Value;
        }
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        //add element to table
        zadania.Add(new Action(start, new DateTime(2008, 6, 1, 8, 30, 52), textbox.Text));
    }

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        //show in datagridview  
        DataGrid.ItemsSource = zadania;
    }
}

That's because zadania is a List<Action> and a List<T> doesn't implement the INotifyCollectionChanged interface. 这是因为zadania是一个List<Action>List<T>没有实现INotifyCollectionChanged接口。

The source collection must implement this interface for items to be automatically added or removed from the view as you call Add and Remove . 源集合必须实现此接口,以便在您调用Add and Remove自动从视图中AddRemove

There is only one built-in collection that does implement this interface, namely the ObservableCollection<T> class. 只有一个内置集合可以实现此接口,即ObservableCollection<T>类。

So if you simply change the type of your source collection, you should be fine: 因此,如果仅更改源集合的类型,就可以了:

public ObservableCollection<Action> zadania = new ObservableCollection<Action>();

Each time you add an item you must refresh the datagrid items. 每次添加项目时,都必须刷新数据网格项目。

private void Button_Click(object sender, RoutedEventArgs e)
{
    //add element to table
    zadania.Add(new Action(start, new DateTime(2008, 6, 1, 8, 30, 52), textbox.Text));
    DataGrid.Items.Refresh();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM