如何在点击后实现StackLayout或Grid中背景颜色平滑变化的效果?如果我们创建一个按钮,它开箱即用 - 我在附加的GIF中显示了这个效果。 ListView中的ViewCell也是如此。点击后它也会产生改变背景颜色的连锁效果。但是如何实现StackLayout或Grid?
如何实现这一目标
解决方案1:
您认为ViewCell具有在单击后更改背景颜色的连锁效果。您可以将Stacklayout或Grid放在只有一个ViewCell的列表视图中。
在xaml
<StackLayout>
<ListView x:Name="listView">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout>
<Label TextColor="Black" Text="{Binding Content}"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
在代码背后
public class Data
{
public string Content { get; set; }
}
public partial class MainPage : ContentPage
{
public ObservableCollection<Data> MySource { get; set; }
public MainPage()
{
InitializeComponent();
BindingContext = this;
MySource = new ObservableCollection<Data>()
{
new Data() {Content="Click Me" },
};
listView.ItemsSource = MySource;
}
}
解决方案2:
你可以使用nuget包TouchView
将nuget包添加到您的Xamarin.Forms .netStandard / PCL项目以及特定于平台的项目(iOS和Android)
iOS:将TouchViewRenderer.Initialize()行添加到AppDelegate(从链接器保留)
using TouchEffect.iOS;
namespace YourApp.iOS
{
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
global::Xamarin.Forms.Forms.Init();
TouchViewRenderer.Initialize();
LoadApplication(new App());
return base.FinishedLaunching(app, options);
}
}
}
在xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:YourApp"
xmlns:touch="clr-namespace:TouchEffect;assembly=TouchEffect"
x:Class="App11.MainPage">
<StackLayout>
<touch:TouchView
RegularBackgroundColor="LightGray"
PressedBackgroundColor="Gray"
PressedOpacity="1"
PressedAnimationDuration="100"
RegularAnimationDuration="100"
Padding="10, 5"
VerticalOptions="CenterAndExpand"
HorizontalOptions="CenterAndExpand"
Completed="Handle_TouchCompleted"
>
<Label Text="Click Me"
TextColor="Black"
FontSize="30"/>
</touch:TouchView>
</StackLayout>
</ContentPage>
在代码背后
private void Handle_TouchCompleted(TouchEffect.TouchView sender, TouchEffect.EventArgs.TouchCompletedEventArgs args)
{
// do something you want
}