Solved

INotifyChanged not firing

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

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
This article describes relatively difficult and non-obvious issues that are likely to arise when creating COM class in Visual Studio and deploying it by professional MSI-authoring tools. It is assumed that the reader is already familiar with the cla…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

759 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

19 Experts available now in Live!

Get 1:1 Help Now