Johnny
Johnny

Reputation: 879

Raise PropertyChanged for a property inside a model

So I've got a TimerModel which holds data for the entity and a TimerViewModel which handles the timer ticks from each one of the timers. It simply decrements the TimeSpan set as the interval for the timer - I'm doing this purely because I need to update the View with the remaining time.

public class TimerModel
{
    public TimerModel(TimeSpan Interval, TimerViewModel Parent)
    {
        Timer = new DispatcherTimer();
        Timer.Interval = TimeSpan.FromSeconds(1);
        parent = Parent;

        this.Interval = Interval;

        Timer.Tick += (sender, args) => parent._timer_Tick(this, args);
        Timer.Start();
    }

    private TimerViewModel parent;

    public DispatcherTimer Timer
    {
        get;
        private set;
    }

    public TimeSpan Interval
    {
        get;
        set;
    }
}

And the TimerViewModel would be:

public class TimerViewModel : ViewModelBase
{
    public TimerViewModel()
    {
        Timers = new ObservableCollection<TimerModel>();
        AddTimerCommand = new RelayCommand((object x) => { AddTimer(x); });
    }

    public ObservableCollection<TimerModel> Timers
    {
        get;
        private set;
    }

    public ICommand AddTimerCommand
    {
        get;
        private set;
    }

    private void AddTimer(object s)
    {
        Timers.Add(new TimerModel(TimeSpan.FromSeconds(250), this));
    }

    internal void _timer_Tick(object sender, EventArgs e)
    {
        TimerModel timer = sender as TimerModel;
        timer.Interval = timer.Interval.Subtract(TimeSpan.FromSeconds(1));
        RaisePropertyChanged("Timers");
    }
}

Which is bound to a listbox:

<ListBox x:Name="lst_timers" Height="300" Width="150" HorizontalAlignment="Left"
DataContext="{Binding local:TimerViewModel}" ItemsSource="{Binding Timers}" 
DisplayMemberPath="Interval" />

_timer_Tick should be raising the property changed for the whole list, but seemingly the listbox items remain unchanged. Can anyone give me a clue what am I missing here?

Upvotes: 0

Views: 998

Answers (2)

Stephan Bauer
Stephan Bauer

Reputation: 9249

The Timers list is not changing, it's the Interval property of the Timer object that changes.

I'd suggest a ViewModel for your whole view (set as DataContext for your window/control..., not for the ListBox inside this parent window/control) containing a property Timers of type ObervableCollection<TimerViewModel>. This TimerViewModel represents one single timer and should raise a PropertyChanged-Event for "Interval" in the property's setter.

(For additional information see comments)

Upvotes: 1

Andy
Andy

Reputation: 3743

<ListBox x:Name="lst_timers" ...>
    <ListBox.DataContext>
      <local:TimerViewModel/> 
    </ListBox.DataContext>
</ListBox>

Upvotes: 1

Related Questions