Enabling/Disabling button using View Model

salilsingh-9961 346 Reputation points
2023-10-30T06:51:01.8766667+00:00

Hi Team,

I am working on a .Net MAUI app (in Visual Studio 2022), Android emulator used is Pixel 5 API 33. Please provide me solution for below -

In XAML page, i need to enable/disable a button using ViewModel, please provide me a link which shows how to achieve it.

Thanks,

Salil

.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
3,386 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 74,316 Reputation points Microsoft Vendor
    2023-10-31T06:18:42.28+00:00

    Hello,

    i need to enable/disable a button using ViewModel, please provide me a link which shows how to achieve it.

    Here is a document about Data binding and MVVM - .NET MAUI | Microsoft Learn, you can refer to it.

    Based on your description, you can add property BtnIsEnabled, if you want to make the value of BtnIsEnabled changed at the runtime, please implement the INotifyPropertyChanged interface like following code.

    public class MyViewModel: INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
    
    
       public void OnPropertyChanged([CallerMemberName] string name = "") =>
      PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    
    
        private bool _btnIsEnable;
    
    
       public bool BtnIsEnabled
        {
            get { return _btnIsEnable; }
            set { _btnIsEnable = value; }
        }
    
    
       public MyViewModel()
        {
        }
    }
    

    Then you can bind this BtnIsEnabled property in your button's IsEnabled attribute.

     <Button IsEnabled="{Binding BtnIsEnabled}" ></Button>
    

    Best Regards,

    Leon Lu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.