Solved

INotifyChanged not firing

Posted on 2011-02-20
5
633 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
  • 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 500 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

The New “Normal” in Modern Enterprise Operations

DevOps for the modern enterprise offers many benefits — increased agility, productivity, and more, but digital transformation isn’t easy, especially if you’re not addressing the right issues. Register for the webinar to dive into the “new normal” for enterprise modern ops.

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…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…

830 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