简体   繁体   中英

WPF Button IsEnabled Binding failed

I want to binding Button IsEnabled to my ViewModel. So I tried this:

<Button Content="{Binding Icon}"  Command="{Binding Connect}" IsEnabled="{Binding ConnectBtnEnable, Mode=TwoWay}" />

And in the viewmodel:

private bool _ConnectBtnEnable = true;
public bool ConnectBtnEnable 
{  
     get { return _ConnectBtnEnable; } 
     set { _ConnectBtnEnable = value; OnPropertyChanged(); } 
}

But when I set the property in the use:

public void Connect()
{ 
    ConnectBtnEnable = false;
}

It doesn't work, What is the problem. Thanks in advance!

In case you are using a command for your button, it's recommended not to separately bind the IsEnabled property of the button. Instead you should provide the correct value in the "CanExecute" method implementation of the command. That should enable or disable the button accordingly.

You can refer this article for a sample ICommand implementation - https://www.codeproject.com/Tips/813345/Basic-MVVM-and-ICommand-Usage-Example

Also, to update a control - make sure to update properties of VM (not member fields); so that the notification updates will be triggered, and the bound target (control state) is updated.

Because you need to set ConnectBtnEnable instead of _ConnectBtnEnable . It is a good example that you should name your private fields in other way than properties. For example, _connectBtnEnable .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM