简体   繁体   中英

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

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.

The source collection must implement this interface for items to be automatically added or removed from the view as you call Add and Remove .

There is only one built-in collection that does implement this interface, namely the ObservableCollection<T> class.

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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