您可以自定义任何属性,如果Button
它是disabled
使用Style
. 更改 的值Opacity
以更改按钮的透明度级别。
<ContentPage.Resources>
<Style x:Key="BaseButton" TargetType="Button">
<Style.Triggers>
<Trigger TargetType="Button"
Property="IsEnabled"
Value="False">
<Setter Property="TextColor" Value="#5019171c" />
<Setter Property="BackgroundColor" Value="Red" />
<Setter Property="Opacity" Value="0.9" />
</Trigger>
</Style.Triggers>
</Style>
</ContentPage.Resources>
<StackLayout>
<!-- Place new controls here -->
<Button Text="click" Clicked="Button_Clicked"/>
<Button Text="sampleButton" BackgroundColor="Blue" x:Name="sampleButton" Style="{StaticResource BaseButton}"/>
</StackLayout>
更新代码:
[assembly: ExportRenderer(typeof(Xamarin.Forms.Button), typeof(LabelButtonRenderer), new[] { typeof(VisualMarker.MaterialVisual) })]
namespace App389.Droid
{
public class LabelButtonRenderer : MaterialButtonRenderer
{
public LabelButtonRenderer(Context ctx) : base(ctx)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
{
base.OnElementChanged(e);
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(Xamarin.Forms.Button.IsEnabled))
{
if (Element.IsEnabled == false) {
Control.BackgroundTintList = Android.App.Application.Context.Resources.GetColorStateList(Resource.Color.button_normalcolor);
}
else
{
Control.BackgroundTintList = Android.App.Application.Context.Resources.GetColorStateList(Resource.Color.button_disablecolor);
}
}
}
}
}
并在 colors.xml 中添加颜色:
<resources>
<color name="launcher_background">#FFFFFF</color>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color>
<color name="button_normalcolor">#ff00</color>
<color name="button_disablecolor">#FF4081</color>
</resources>
更新 iOS 代码:
[assembly: ExportRenderer(typeof(Xamarin.Forms.Button), typeof(LabelButtonRenderer), new[] { typeof(VisualMarker.MaterialVisual) })]
public class LabelButtonRenderer : MaterialButtonRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
{
base.OnElementChanged(e);
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
Console.WriteLine(e.PropertyName.ToString());
if (e.PropertyName == nameof(Xamarin.Forms.Button.IsEnabled))
{
Control.BackgroundColor = Element.BackgroundColor.ToUIColor();
}
}
}