Arvind Chourasiya
Arvind Chourasiya

Reputation: 17382

Modify button background through triggers Xamarin forms

I have two buttons. I want change second Button BackgroundColor using Triggers When I click first button but I am unable to do it. The code I am trying

<Button  Text="button 1" x:Name="btn1"  HorizontalOptions="Fill">
    <Button.Triggers>
        <Trigger TargetType="Button" Binding="{Binding Source={x:Reference btn2} Property="IsEnabled">
            <Setter Property="BackgroundColor" Value="Red"></Setter>
        </Trigger>
    </Button.Triggers>
</Button>
<Button  Text="button 2" x:Name="btn2" HorizontalOptions="Fill" />

I even have no idea where to write click event for this.

Upvotes: 1

Views: 2744

Answers (1)

NKR
NKR

Reputation: 2943

The best way to do that is to use ViewModel rather than the Code base.

Approach 1 : using the ViewModel

public class YourViewModel : BaseViewModel
{

    public ICommand Button1Command { get; set; }

    private bool _enableButton2;
    public bool EnableButton2
    {
        get
        {
            return _enableButton2;
        }
        set
        {
            _enableButton2= value;
            RaisePropertyChanged();
        }
    }

    public YourViewModel()
    {
         Button1Command =new Command(Button1Clicked);
    }


    private void Button1Clicked()
    {
        EnableButton2=true;    //Whenever you need to enable or disable set it true/false
    }

}

Now you have your ViewModel, You need to implement your UI like this :

<Button x:Name="button1" Text="Button 1" Command="{Binding Button1Command }" />
<Button x:Name="button2" Text="Button 2">
  <Button.Triggers>
     <DataTrigger TargetType="Button" Binding="{Binding EnableButton2}" Value="false">
        <Setter Property="BackgroundColor"  Value="#dbe1e5" />
        <Setter Property="TextColor"  Value="#bfcfd5" />
      </DataTrigger>
      <DataTrigger TargetType="Button" Binding="{Binding EnableButton2" Value="true">
          <Setter Property="BackgroundColor"  Value="Red" />
           <Setter Property="TextColor"  Value="#FFFFFF" />
       </DataTrigger>
   </Button.Triggers>

</Button>

This is the MVVM way to do this; let me know if you want Code Base style.

Upvotes: 5

Related Questions