1

I'm newer to MVVM design pattern , I have a class User and a property IsEnabled,

I will use this class later in a ViewModel , what I would like to know if is it possible to initialize a property change in this class ( As an example Set IsEnabled to True )

 public  class User : INotifyPropertyChanged
    {
        public int UserId { get; set; }
        public string UserName { get; set; }
 public event PropertyChangedEventHandler PropertyChanged;

        private bool isEnabled;
        public bool IsEnabled
        {
            get { return isEnabled; }
            set
            {
                if (isEnabled != value)
                {
                    isEnabled = value;
                    OnPropertyChanged("IsEnabled");
                }
            }
        }
        protected void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null) 
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

The class compiles without any errors :

enter image description here

1 Answers1

0

Change the declaration of your backing property:

private bool isEnabled = true;

Then the initial value as applied to the DataContext and thus to any Binding extensions will propagate the true value.

Andrew H
  • 875
  • 5
  • 20
  • This is just a copy of clemens comment. – Andy Sep 27 '21 at 17:33
  • I didn't copy any comments. I provided a simple solution to a straightforward problem. – Andrew H Sep 27 '21 at 17:39
  • @Andy comments are not for answering questions. I don't understand the logic of some users choosing to answer questions in comments when it completely misses the purpose of comments to ask for clarification from the asker. It's unfair to criticize me for posting a solution any developer could have come up with because I chose to use the correct avenue for posting that answer after someone else who didn't. – Andrew H Sep 27 '21 at 23:20
  • Some questions are trivial. They shouldn't really be question at all. The obvious answer to this is just set the field. That's one line. Some questions you have to just guess what the poster means. Ask them to explain or qualify as much as you like and they don't. – Andy Sep 28 '21 at 08:04
  • You're right, they may be trivial and they probably shouldn't be a question, but we're still here discussing the answer to such a trivial question :) I did not read through 10+ comments on such a simple question to find an identical answer and feel the selfish need to copy someone else's answer. I provided the answer any other semi-experienced developer would have provided, regardless of whether someone else incorrectly provided the answer as a comment. – Andrew H Sep 28 '21 at 16:20