Xamarin 窗体透明按钮隐藏图像



>我有一个包含图像和按钮的框架,但即使按钮的背景颜色设置为透明,它仍然隐藏了它后面的图像,我一直无法弄清楚为什么会这样。删除按钮可使图像看起来很好。

<Grid x:Name="SettingsGrid" Grid.Row="1"  Grid.Column="1" BackgroundColor="Transparent" Grid.RowSpan="2">
<Frame x:Name="SettingsFrame" CornerRadius="42" HasShadow="false" BackgroundColor="#aa2129" Padding="0">
<Image Source="whitecog.PNG" HorizontalOptions="Center" VerticalOptions="Center" Scale="1"/>
<Button x:Name="SettingsButton" Clicked="OnSettingsClick"
HorizontalOptions="Center" VerticalOptions="Center"
BorderWidth="1"  BorderColor="Transparent" BackgroundColor="Transparent" BorderRadius="0"/>
</Frame>
</Grid>

如果你只需要在两个图像之间切换 - 你可以扩展Grid以使用TapGestureRecognizer(我已经在 C# 中实现了这一点,但你也可以在 XAML 中做同样的事情)。

public class ToggleImage : Grid
{
public static readonly BindableProperty ToggledSourceProperty = BindableProperty.Create("ToggledSource", typeof(ImageSource), typeof(Image), default(ImageSource), propertyChanged: OnValueChanged);
public static readonly BindableProperty OriginalSourceProperty = BindableProperty.Create("OriginalSource", typeof(ImageSource), typeof(Image), default(ImageSource), propertyChanged: OnValueChanged);
public static readonly BindableProperty IsToggledProperty = BindableProperty.Create("IsToggled", typeof(bool), typeof(Image), false, defaultBindingMode: BindingMode.TwoWay, propertyChanged: OnValueChanged);
private Image _originalImage;
private Image _toggledImage;
public ToggleImage()
{
var tapRecognizer = new TapGestureRecognizer();
tapRecognizer.Command = new Command(() => IsToggled = !IsToggled);
GestureRecognizers.Add(tapRecognizer);
_originalImage = new Image { Aspect = Aspect.AspectFit };
_toggledImage = new Image { Aspect = Aspect.AspectFit };
Children.Add(_originalImage);
Children.Add(_toggledImage);
}
static void OnValueChanged(BindableObject bindable, object oldValue, object newValue)
{
var ctrl = bindable as ToggleImage;
if (ctrl == null)
return;
ctrl.OnValueChanged();
}
void OnValueChanged()
{
_originalImage.Source = OrginalSource;
_toggledImage.Source = ToggledSource;
_toggledImage.IsVisible = IsToggled;
_originalImage.IsVisible = !IsToggled;
}
public bool IsToggled
{
get { return (bool)GetValue(IsToggledProperty); }
set { SetValue(IsToggledProperty, value); }
}
public ImageSource ToggledSource
{
get { return (ImageSource)GetValue(ToggledSourceProperty); }
set { SetValue(ToggledSourceProperty, value); }
}
public ImageSource OrginalSource
{
get { return (ImageSource)GetValue(OriginalSourceProperty); }
set { SetValue(OriginalSourceProperty, value); }
}
}

示例用法:

<Grid x:Name="SettingsGrid" Grid.Row="1"  Grid.Column="1" BackgroundColor="Transparent" Grid.RowSpan="2">
<Frame x:Name="SettingsFrame" CornerRadius="42" HasShadow="false" BackgroundColor="#aa2129" Padding="0">
<local:ToggleImage IsToggled="{Binding IsToggled}" OriginalSource="image1.png" ToggledSource="image2.png" HorizontalOptions="Center" VerticalOptions="Center" Scale="1"/>
</Frame>
</Grid>  

最新更新