简体   繁体   English

为什么对数据库进行更改时我的绑定没有更新?

[英]Why is my Binding not updating when changes are made to database?

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. 我已经搜索了几个小时,但仍然不知道为什么在对数据库进行更改时,为什么它没有立即反映在ListBox中的TextBlock项上。

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 这是我的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. TextBlock显示分配的Event.Name,但是当我更改数据库中的数据时,直到重新初始化绑定才进行更改。

A WPF binding binds the UI to the ViewModel . WPF绑定将UI绑定到ViewModel Changes in the model (database or other data source) will not automatically notify the ViewModel. model (数据库或其他数据源)中的更改将不会自动通知ViewModel。 And If the ViewModel does not know of the changes, it cannot update the UI through the binding. 而且,如果ViewModel不知道更改,则无法通过绑定更新UI。

If you need to react on changes in your model, you will need to find a way to notify your viewmodel of those changes. 如果您需要对模型中的更改做出反应,则需要找到一种方法将这些更改通知您的视图模型。

As suggested by others, you would need to notify viewmodel if your model (database) updates. 正如其他人所建议的那样,如果模型(数据库)更新,则需要通知viewmodel。

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. 一个简单的解决方案可能是在模型(获取/设置数据库)中具有Updated事件,然后您的viewmodel将处理程序附加到该事件。 On recieving any update, ViewModel would re-initialize itself which will get reflected in UI. 收到任何更新后,ViewModel将重新初始化自身,这将反映在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?... 您在使用任何ORM吗?...

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

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