Question

I have searched for hours and still do not know why when changes are made to my database why it is not reflecting immediately on the TextBlock item in my ListBox.

Here is my class:

class Event : INotifyPropertyChanged
{
   public string Name { get; set; }
   public event PropertyChangedEventHandler PropertyChanged;

    public string CustomerName
    {
        get
        {
            return this.Name;
        }

        set
        {
            if (value != this.Name)
            {
                this.Name = value;
                NotifyPropertyChanged("CustomerName");
            }
        }
    }

    private void NotifyPropertyChanged(String propertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Here is my xaml
<ListBox x:Name="lb_events" ItemTemplate="{DynamicResource EventsTemplate}"...
<DataTemplate x:Key="EventsTemplate"...<StackPanel><TextBlock Text="{Binding CustomerName, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"

The TextBlock displays the Event.Name assigned, but when I change the data in the database, changes are not made until I reinitialize the binding.

Was it helpful?

Solution

As suggested by others, you would need to notify viewmodel if your model (database) updates.

Would you recommend a method to keep refreshing the window to show the update?

A simple solution could be to have Updated event in your model (which gets/sets database), and then your viewmodel will attach a handler to this event. On recieving any update, ViewModel would re-initialize itself which will get reflected in UI.

If your design doesn't support updating model when database is updated. Then it is bigger design quesion really. For instance, how database is updated? are you using any ORM?...

OTHER TIPS

A WPF binding binds the UI to the ViewModel. Changes in the model (database or other data source) will not automatically notify the ViewModel. And If the ViewModel does not know of the changes, it cannot update the UI through the binding.

If you need to react on changes in your model, you will need to find a way to notify your viewmodel of those changes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top