我在(XAML)中使用转换器来实现这一点,对于您的情况应该是相同/类似的。通常会结合IsEnabled
和Opacity
,因为我喜欢使禁用的按钮更透明。
例如,您可以创建两个转换器来解释字符串(输入字段中的文本)。
第一个转换器将确定文本是否为空,并在有文本时返回true。
public class StringToBoolConverter
: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return !string.IsNullOrEmpty(value?.ToString());
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
第二个转换器将确定不透明度水平,在文本存在时返回100%(例如:
1.0
),当字段为空时返回
0.3
。
public class StringToFloatConverter
: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return !string.IsNullOrEmpty(value?.ToString())? 1.0 : 0.3;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
现在我在App.xaml
中为两个转换器都打上更有意义的名称,如下所示:
<?xml version="1.0" encoding="utf-8" ?>
<Application xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:converters="clr-namespace:Sasw.EasyQr.Converters;assembly=Sasw.EasyQr"
mc:Ignorable="d"
x:Class="Sasw.EasyQr.App">
<Application.Resources>
<ResourceDictionary>
<converters:StringToBoolConverter x:Key="EnabledWhenFilledConverter"></converters:StringToBoolConverter>
<converters:StringToFloatConverter x:Key="OpaqueWhenFilledConverter"></converters:StringToFloatConverter>
</ResourceDictionary>
</Application.Resources>
</Application>
现在我可以从任何按钮控件中引用这些转换器,例如:
<Entry
Text = "{Binding Text}"
Placeholder="{x:Static resources:AppResources.PlaceholderEnterText}"
HorizontalOptions="FillAndExpand"
VerticalTextAlignment="Center"
VerticalOptions="End"></Entry>
<ImageButton
Command="{Binding TapClear}"
IsEnabled="{Binding Text, Converter={StaticResource EnabledWhenFilledConverter}}"
Source ="backspace.png"
WidthRequest="30"
Opacity="{Binding Text, Converter={StaticResource OpaqueWhenFilledConverter}}"
BackgroundColor="Transparent"
HorizontalOptions="End"
VerticalOptions="CenterAndExpand"></ImageButton>
观察当在输入框中输入文本时,按钮将自动变为可用并不透明,而当文本被删除时则会被禁用并变为透明。
![button transparent and disabled](https://istack.dev59.com/JxT4F.webp)
![button enabled and opaque](https://istack.dev59.com/Ahl85.webp)