通过触发 Xamarin 表单修改按钮背景 [英] Modify button background through triggers Xamarin forms

查看:27
本文介绍了通过触发 Xamarin 表单修改按钮背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个按钮.我想更改第二个 Button BackgroundColor 使用 Triggers 当我点击第一个按钮但我无法做到.我正在尝试的代码

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.

推荐答案

最好的方法是使用 ViewModel 而不是代码库.

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

方法一:使用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
    }

}

现在你有了你的 ViewModel,你需要像这样实现你的 UI:

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>

这是执行此操作的 MVVM 方式;如果您想要代码库样式,请告诉我.

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

这篇关于通过触发 Xamarin 表单修改按钮背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆