Solved

INotifyChanged not firing

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Eagerly loading related objects in entity framework 5 26
Visual Studio 2015 Source Code Control 10 34
Variable Event ? 3 23
Close form "before" open 3 25
Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
This Micro Tutorial will teach you how to censor certain areas of your screen. The example in this video will show a little boy's face being blurred. This will be demonstrated using Adobe Premiere Pro CS6.
Internet Business Fax to Email Made Easy - With  eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, f…

920 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

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now