问题描述
当我在集合视图中添加SelectionChanged
函数时,visualstatemanager
不起作用。
<ContentPage.Resources>
<Style targettype="StackLayout">
<Setter Property="visualstatemanager.VisualStateGroups">
<VisualStateGroupList>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="normal" />
<VisualState x:Name="Selected">
<VisualState.Setters>
<Setter Property="BackgroundColor" Value="LightSkyBlue"/>
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateGroupList>
</Setter>
</Style>
</ContentPage.Resources>
当我在CollectionView
:SelectionChanged="OnCollectionViewSelectionChanged"
中添加此代码时,visualstatemanager
停止工作。有人知道为什么吗?
解决方法
该问题导致SelectionChanged
无法获得所选元素类型,例如StackLayout
或Label
。您可以改用TapGestureRecognizer
。
Xaml:
<ContentPage.Resources>
<Style TargetType="StackLayout">
<Setter Property="VisualStateManager.VisualStateGroups">
<VisualStateGroupList>
<VisualStateGroup>
<VisualState x:Name="Selected">
<VisualState.Setters>
<Setter Property="BackgroundColor" Value="Accent" />
</VisualState.Setters>
</VisualState>
<VisualState x:Name="UnSelected">
<VisualState.Setters>
<Setter Property="BackgroundColor" Value="Blue" />
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateGroupList>
</Setter>
</Style>
</ContentPage.Resources>
<ContentPage.Content>
<StackLayout
Padding="10"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand">
<CollectionView
x:Name="MenuCollection"
ItemsSource="{Binding Infos}"
SelectionChanged="MenuCollection_OnSelectionChanged"
SelectionMode="Single"
VerticalScrollBarVisibility="Always">
<CollectionView.ItemsLayout>
<GridItemsLayout
HorizontalItemSpacing="15"
Orientation="Vertical"
Span="2"
VerticalItemSpacing="15" />
</CollectionView.ItemsLayout>
<CollectionView.ItemTemplate>
<DataTemplate>
<StackLayout BackgroundColor="Blue">
<Label Text="{Binding Title}" />
<StackLayout.GestureRecognizers>
<TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped" />
</StackLayout.GestureRecognizers>
</StackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</StackLayout>
</ContentPage.Content>
背后的代码:
public partial class Page4 : ContentPage
{
public ObservableCollection<Info> Infos { get; set; }
public Page4()
{
InitializeComponent();
Infos = new ObservableCollection<Info>
{
new Info(){ Title="A"},new Info(){ Title="B"},new Info(){ Title="C"},new Info(){ Title="D"}
};
this.BindingContext = this;
}
StackLayout lastElementSelected;
private void MenuCollection_OnSelectionChanged(object sender,SelectionChangedEventArgs e)
{
}
private void TapGestureRecognizer_Tapped(object sender,EventArgs e)
{
if (lastElementSelected != null)
VisualStateManager.GoToState(lastElementSelected,"UnSelected");
VisualStateManager.GoToState((StackLayout)sender,"Selected");
lastElementSelected = (StackLayout)sender;
}
}
public class Info
{
public string Title { get; set; }
}
截屏: