Hello,
How to change background color of WebView on SelectionChanged event of CollectionView
Because each time you tap the item in CollectionView, you can just select the outer Grid which has been defined in DataTemplate. Then webview background color won't change as it doesn't receive a state change.
You can add a style in the current contentpage's Resources.
<ContentPage.Resources>
<Style TargetType="StackLayout">
<Setter Property="VisualStateManager.VisualStateGroups">
<VisualStateGroupList>
<VisualStateGroup x:Name="CommonStates">
<VisualState Name="Normal">
<VisualState.Setters>
<Setter TargetName="myWebview" Property="WebView.Background" Value="White" />
</VisualState.Setters>
</VisualState>
<VisualState Name="Selected">
<VisualState.Setters>
<Setter TargetName="myWebview" Property="WebView.Background" Value="#E1E1E1" />
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateGroupList>
</Setter>
</Style>
</ContentPage.Resources>
Note: In DataTemplate of CollectionView, remember to set the name of the Webview to "myWebview" as we used it in the ContentPage.Resources.
By the way, if you put grid in the DataTemplate directly, when you selected it, the default selected orange color will appear, so I use <StackLayout>
to wrap it.
<CollectionView ItemsSource="{Binding Models}" SelectionMode="Single">
<CollectionView.ItemTemplate>
<DataTemplate>
<StackLayout BackgroundColor="White">
<Grid>
<Label TextType="Html" FontSize="22"
Padding="5" LineHeight="1.5" LineBreakMode="WordWrap" Margin="2"
Text="{Binding DisplayForWebView}" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" />
<WebView x:Name="myWebview" Margin="0" VerticalOptions="StartAndExpand" >
<WebView.Source>
<HtmlWebViewSource Html="{Binding DisplayForWebView}" />
</WebView.Source>
</WebView>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup>
<VisualState Name="Normal">
<VisualState.Setters>
<Setter Property="BackgroundColor" Value="White" />
</VisualState.Setters>
</VisualState>
<VisualState Name="Selected">
<VisualState.Setters>
<Setter Property="BackgroundColor" Value="#E1E1E1" />
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
</Grid>
</StackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
Best Regards,
Leon Lu
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.