Search code examples
wpfmvvmdatagridtaskbindinglist

Create a countdown timer column in WPF datagrid MVVM


I've been working with datagridview and binding its source to BindingList. I am having a problem updating the datagrid's Timer Column value. Every time I change the Timer's value, datagrid does not update. I already tried many solutions and I came up with the following code but still no good:

Here's my XAML:

<DataGrid ItemsSource="{Binding MyList}">
    <DataGridTextColumn Header="Timer" Binding="{Binding Path=Countdown, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</DataGrid>

Here's my Class:

public class MyClass
{
    public string Countdown {get;set;}
}

Here's my ViewModel:

public class MyViewModel
{
    private BindingList<MyClass> _myList;
    public BindingList<MyClass> MyList
    {
        get { return _myList; }
        set
        {
            _myList= value;
            NotifyOfPropertyChange(() => MyList); //I am using Caliburn's Screen
        }
    }
}

Here's how I changed the property:

void OnButtonClick()
{
    var fireAndForget = Task.Run(async () =>
    {
        int currentRowIndex = 0; 
        for (int i = 30; i > 0; i--)
        {
            MyList[currentRowIndex].CountDown = i.ToString();
            MyList.ResetBindings();
            await Task.Delay(1000);
        }
    }
}

This only displays 30 in the Timer Column and does not update.

I also tried using TrulyObservableCollection and FullyObservableCollection, both no good. I also tried changing the whole MyList by creating a localMyList and doing MyList = localMyList but still not updating


Solution

  • You have forgotten to notify the property is changed. So do

    public class MyClass
    {
        private string _countdown;
        public string Countdown
        {
            get { return _countdown; }
            set
            {
                _countdown = value;
                NotifyOfPropertyChange(() => Countdown);
            }
        }
    }