Why is INotifyPropertyChanged not updating the variables in XAML?

北慕城南 提交于 2019-11-30 10:37:40
Gishu

Maybe I'm not getting what you wish this code to do.

You have created a Customer Object which implements INotifyPropertyChanged. You have another class which is a factory for the XAML to get to the instance. Now you create a Customer instance with predefined properties. The View displays them. Unless you change the properties somehow, the View will not update.

I added a button to your WPF View

<Button DockPanel.Dock="Bottom" 
        x:Name="UpdateTime" 
        Click="UpdateTime_Click">
                 Update Activity Timestamp
 </Button>  

C# code-behind:

private void UpdateTime_Click(object sender, RoutedEventArgs e)
{
     Customer.GetCurrentCustomer().TimeOfMostRecentActivity = DateTime.Now;
}

I also changed Customer type to create a single instance for Current Customer

private static Customer _CurrentCustomer;

public static Customer GetCurrentCustomer()
{
    if (null == _CurrentCustomer)
    {
        _CurrentCustomer = new Customer 
        {   FirstName = "Jim"
           , LastName = "Smith"
           , TimeOfMostRecentActivity = DateTime.Now 
         };
    }
         return _CurrentCustomer;
}

Now each time I click the button, the DateTime Property is modified and the view auto-updates due to the INotifyPropertyChanged mechanism. The code seems to be working AFAISee.

Sacha Bruttin

Your code is working correctly. The current date and time will not update automatically by magic. You have to implement some timer to update it.

For exemple you could add this to your Customer class:

private Timer _timer;

public Customer()
{
    _timer = new Timer(UpdateDateTime, null, 0, 1000);
}

private void UpdateDateTime(object state)
{
    TimeOfMostRecentActivity = DateTime.Now;
}

You seem to be binding to Customer, and Customer doesn't implement INotifyPropertyChanged. Try implementing INotifyPropertyChanged on Customer, and see if that fixes it. This will require moving to manual properties (rather than automatically implemented properties) in order to raise the event.

Can you check how many times GetCurrentCustomer() gets called? Maybe it just re-creates new instances all the time.

Your customer class needs to implement INotifyPropertyChanged and you need to invoke the event during the setter methods of the properties of Customers.

Edit: Have looked at you code again, I wonder whether your ShowCustomerViewModel class needs to listen to the _currentCustomer PropertyChanged event and forward it as its own PropertyChangedEvent. Worth a shot.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!