?
Solved

INotifyChanged not firing

Posted on 2011-02-20
5
Medium Priority
?
636 Views
Last Modified: 2012-05-11
I'm trying to move to the MVVM method of programming in Silverlight 4, but have come across an issue on my first attempt.

I have my ViewModel, detailed below, but when the 'iscompleted' Boolean is set to true, the change is not being detected by the view. In the view I have applied a binding to 'isCompleted', for the isEnabled property of a button, but this never changes even though I know the iscomplted boolean is being set to true.

Can anyone tell me where I've gone wrong here.
public class infoDisplayViewModel : INotifyPropertyChanged
    {
        #region " Data Members "

        public event PropertyChangedEventHandler PropertyChanged; // Interface member :Require to implement this         

        
        private ObservableCollection<Image> imageList = new ObservableCollection<Image>();
        //private ObservableCollection<UploadFile> wbList = new ObservableCollection<UploadFile>();
        private Boolean iscompleted;
        private BackgroundWorker _backgroundWorker = new BackgroundWorker();
        private Int32 count;
        const int CHUNKSIZE = 30000; //30KB

        #endregion

        #region " Default Constructor "
        /// <summary>
        /// 
        /// </summary>
        public infoDisplayViewModel()
        {
            if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(System.Windows.Application.Current.RootVisual))
            {
                LoadZipfile();
            }
            //CreateBackgroundworker();
        }

        #endregion

        
        #region " Zip Handling Methods "
        private void LoadZipfile()
        {
            iscompleted = false;
            WebClient c = new WebClient();
            c.OpenReadCompleted += new OpenReadCompletedEventHandler(openReadCompleted);
            c.OpenReadAsync(new Uri(Application.Current.Host.Source, "../Zips/Images.zip"));
        }

        private void openReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {

            if (e.Error == null)
            {
                
                WebClient c = (WebClient)sender;
                c.OpenReadCompleted -= openReadCompleted;

                UnZipper unzip = new UnZipper(e.Result);
                //UploadFile up;
                count=0;
                foreach (string filename in unzip.GetFileNamesInZip())
                {
                    Stream stream = unzip.GetFileStream(filename);
                    StreamReader reader = new StreamReader(stream);
                    WriteableBitmap wb;
                    wb = ImageHelper.GetImageSource(stream, 1080, 1080);
                    //up=new UploadFile();
                    
                    //    up.Name = filename;
                    //    up.WBContent=wb;
                    
                    //wbList.Add(up);
                    //BitmapImage bi = new BitmapImage();
                    //bi.SetSource(stream);
                    imageList.Add(new Image() { Source = wb ,Name=filename,Height=500,Width=500, Stretch=Stretch.Uniform});
                    stream.Close();
                    wb = null;
                    //string contents = reader.ReadToEnd();
                    //MessageBox.Show(contents);
                    count++;
                }

                //Set Completed when ready
                iscompleted = true;
                
            }
            else
            {
                new errorHandling().WCFError("The following error occured trying to gather Images from the Server Zip: " + e.Error, "Image Zip File Error", false);
            
            }
        }
#endregion

                 

        #region " Images Property "
        /// <summary>
        /// 
        /// </summary>
        public ObservableCollection<Image> ImageList
        {
            get { return imageList; }
            set
            {
                imageList = value;
                RaisePropertyChanged("ImageList");
            }
        }
 
        
        
        #endregion
        #region " Counter Property "
        /// <summary>
        /// 
        /// </summary>
        public Int32 Count
        {
            get { return count; }
            set
            {
                count = value;
                RaisePropertyChanged("Count");
            }
        }
        #endregion
        #region " Completed Property "
        /// <summary>
        /// 
        /// </summary>
        public Boolean isCompleted
        {
            get { return iscompleted; }
            set
            {
                iscompleted = value;
                RaisePropertyChanged("isCompleted");
            }
        }
        #endregion
        

        #region INotifyPropertyChanged Members


        private void RaisePropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));

        }
        #endregion

Open in new window

0
Comment
Question by:wint100
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
5 Comments
 
LVL 4

Expert Comment

by:grishav
ID: 34941173
In your class you have iscompleted boolean field and isCompleted boolean property.
In the setter of the property you correctly put call to RaisePropertyChanged.
But in openReadCompleted and LoadZipFile function you assign value to the field (iscompleted) and not to the property (isCompleted).
So the property setter isn't executed.
Good luck.
0
 
LVL 1

Author Comment

by:wint100
ID: 34941588
I thought I should be setting the private boolean in the completed event? Is this not the case?

To get things working I added the raisepropertychange("isCompleted") code to the completed event. This got it working but maybe I need to review my knowledge on MVVM patterns.
0
 
LVL 4

Expert Comment

by:grishav
ID: 34941615
That's exactly what your property seter does : sets the private boolean field and calls RaisePropertyChange.
So you actually duplicated this code in your openReadCompleted function. Of course, this works but it's definitely not a good practice...
You should set the value of the property and this, in turn, will set the value of the field.

I personally prefer always to deal with the properties, using private backing fields only in property's getter and setter. Then if I later need to change my code (for example, to raise property change of some other connected property whenever the first one changes), I need to do it only in one place.
0
 
LVL 1

Author Comment

by:wint100
ID: 34941643
Can you give an example of you'd do this, i'm slightly confused.
0
 
LVL 4

Accepted Solution

by:
grishav earned 2000 total points
ID: 34941708
Your code, revised:

public class infoDisplayViewModel : INotifyPropertyChanged
    {
        #region " Data Members "

        public event PropertyChangedEventHandler PropertyChanged; // Interface member :Require to implement this        

       
        private ObservableCollection<Image> imageList = new ObservableCollection<Image>();
        //private ObservableCollection<UploadFile> wbList = new ObservableCollection<UploadFile>();

        // used only as a backing field for the property and never in a real code
        private Boolean iscompleted;

        private BackgroundWorker _backgroundWorker = new BackgroundWorker();
        private Int32 count;
        const int CHUNKSIZE = 30000; //30KB

        #endregion

        #region " Default Constructor "
        /// <summary>
        ///
        /// </summary>
        public infoDisplayViewModel()
        {
            if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(System.Windows.Application.Current.RootVisual))
            {
                LoadZipfile();
            }
            //CreateBackgroundworker();
        }

        #endregion

       
        #region " Zip Handling Methods "
        private void LoadZipfile()
        {
            //iscompleted = false;
            isCompleted = false;
     
      WebClient c = new WebClient();
            c.OpenReadCompleted += new OpenReadCompletedEventHandler(openReadCompleted);
            c.OpenReadAsync(new Uri(Application.Current.Host.Source, "../Zips/Images.zip"));
        }

        private void openReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {

            if (e.Error == null)
            {
               
                WebClient c = (WebClient)sender;
                c.OpenReadCompleted -= openReadCompleted;

                UnZipper unzip = new UnZipper(e.Result);
                //UploadFile up;
                count=0;
                foreach (string filename in unzip.GetFileNamesInZip())
                {
                    Stream stream = unzip.GetFileStream(filename);
                    StreamReader reader = new StreamReader(stream);
                    WriteableBitmap wb;
                    wb = ImageHelper.GetImageSource(stream, 1080, 1080);
                    //up=new UploadFile();
                   
                    //    up.Name = filename;
                    //    up.WBContent=wb;
                   
                    //wbList.Add(up);
                    //BitmapImage bi = new BitmapImage();
                    //bi.SetSource(stream);
                    imageList.Add(new Image() { Source = wb ,Name=filename,Height=500,Width=500, Stretch=Stretch.Uniform});
                    stream.Close();
                    wb = null;
                    //string contents = reader.ReadToEnd();
                    //MessageBox.Show(contents);
                    count++;
                }

                //Set Completed when ready
                //iscompleted = true;
                isCompleted = true;
               
           }
            else
            {
                new errorHandling().WCFError("The following error occured trying to gather Images from the Server Zip: " + e.Error, "Image Zip File Error", false);
           
            }
        }
#endregion

                 

        #region " Images Property "
        /// <summary>
        ///
        /// </summary>
        public ObservableCollection<Image> ImageList
        {
            get { return imageList; }
            set
            {
                imageList = value;
                RaisePropertyChanged("ImageList");
            }
        }
 
       
       
        #endregion
        #region " Counter Property "
        /// <summary>
        ///
        /// </summary>
        public Int32 Count
        {
            get { return count; }
            set
            {
                count = value;
                RaisePropertyChanged("Count");
            }
        }
        #endregion
        #region " Completed Property "
        /// <summary>
        ///
        /// </summary>
        public Boolean isCompleted
        {
            get { return iscompleted; }
            set
            {
                iscompleted = value;
                // in this way, each and every time the value changed you notify your gui about the change
                // You can do it here in one single call - no need to duplicate the code.
   

                RaisePropertyChanged("isCompleted");
            }
        }
        #endregion
       

        #region INotifyPropertyChanged Members


        private void RaisePropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));

        }
        #endregion
0

Featured Post

Is Your Team Achieving Their Full Potential?

74% of employees feel they are not achieving their full potential. With Linux Academy, not only will you strengthen your team's core competencies but also their knowledge of of the newest IT topics.

With new material every week, we'll make sure that you stay ahead of the game.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Add bar graphs to Access queries using Unicode block characters. Graphs appear on every record in the color you want. Give life to numbers. Hopes this gives you ideas on visualizing your data in new ways ~ Create a calculated field in a query: …
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…
Suggested Courses

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question