Solved

INotifyChanged not firing

Posted on 2011-02-20
5
632 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

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

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

Suggested Solutions

Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
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.
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

832 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