Hanna Bilous
Hanna Bilous

Reputation: 328

Bind IsEnabled property for Button in WPF

I have a Button which needs to be enabled/disabled programmatically. I want to achieve this using a binding to a bool. Here is the Button XAML:

<Button x:Name="logInButton" Height="30" IsEnabled="{Binding IsLoggedIn}">
                            <Image Source="/images/img.png"></Image>
                        </Button>

Here is the code being called:

        public MainWindow()
        {
            InitializeComponent();
            enabled = false;
        }
        private bool enabled;
        public bool IsLoggedIn
        {
            get
            {
                return enabled;
            }
            set
            {
                enabled = value;
            }
        } 

The value of the property IsLoggedIn is assigned correctly. But IsEnabled is not assigned the value I need. For example:
For example

I tried setting the value with Binding Path and Binding Source but nothing is working.

Please advise what may be wrong.

Upvotes: 6

Views: 9729

Answers (2)

Hanna Bilous
Hanna Bilous

Reputation: 328

Then... I think must be so.

class Model : INotifyPropertyChanged
    {
        public bool enabled;
        public bool IsLoggedIn
        {
            get
            {
                return enabled;
            }
            set
            {
                enabled = value;
                OnPropertyChanged("IsLoggedIn");
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;
        public void OnPropertyChanged([CallerMemberName]string property = "")
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(property));
        }
    }

Upvotes: 8

Mikkel K.
Mikkel K.

Reputation: 373

Two things are missing:

  1. The IsLoggedIn property should be in DataContext object. In MVVM, this means it should be in the view model.
  2. The DataContext should implement INotifyPropertyChanged so the view can change when you update the property programatically.

Upvotes: 5

Related Questions