Binding of Button Background Color not working in XAML and ViewModel

Riffy 276 Reputation points
2022-05-18T19:13:31.893+00:00

Hi

I am using several Buttons in my XAML whose properties which get updated using binding variables. Example of one button :

<Button Grid.Row="0"  Grid.Column="0" Text="{Binding MText1}" Style="{StaticResource MButton}" BackgroundColor="{Binding MButtBckColor1}" ClassId="{Binding MId1}" Clicked="MButton_Clicked"/>

The binding is as follows:

 string mButtBckColor1 = string.Empty;

        public string MButtBckColor1
        {
            get { return mButtBckColor1; }
            set {mButtBckColor1 = value ; OnPropertyChanged(nameof(mButtBckColor1)); }
        }

   

When updating the BackgroundColor in my ViewModel, this does not work:

 string BackColor = "DarkCyan";
MButtBckColor1 = BackColor;

The other bindings for the Button are working fine

I have searched online for solutions, but none seem to work without build errors. I know the issue is with string being assinged to color type.

Can anyone help me resolve this.

Thanks

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,296 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 68,741 Reputation points Microsoft Vendor
    2022-05-19T02:46:25.177+00:00

    Hello,​

    ===========
    Update=========

    Do you change the background color to grey in Clicked="MButton_Clicked"? If so, please do not use click event and data binding at the same time.

    Please create a new Command in viewmodel for button click.

       <Button Text="{Binding MText1}" Style="{StaticResource MButton}" BackgroundColor="{Binding MButtBckColor1}" Command="{Binding ChangeColorMCommand}"></Button>  
    

    Create a command in your viewModel.

       public ICommand ChangeColorMCommand { private set; get; }  
         
               public MyViewModel()  
               {  
         
                   MText1 = "Color Test";  
                   MButtBckColor1 = Xamarin.Forms.Color.DarkCyan;  
         
                   ActionMCommand = new Command(() => ResetCellsData());  
         
                   ChangeColorMCommand = new Command(() => { MButtBckColor1 = Xamarin.Forms.Color.Gray; });  
               }  
    

    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.