【发布时间】:2021-01-24 09:48:45
【问题描述】:
我有一个带有 SelectionChanged 事件的 CollectionView,一旦选择或取消选择某些项目,就应该读取该事件。实际上,只要包含 CollectionView 的页面打开,应用程序就会进入该事件。如何解决?
xaml
<CollectionView
x:Name="CategoryView"
RelativeLayout.WidthConstraint="{ConstraintExpression
Type=RelativeToParent,
Property=Width,
Factor=1}"
RelativeLayout.YConstraint="{ConstraintExpression
Type=Constant,
Constant=60}"
Margin="10,0,10,0"
HeightRequest="700"
SelectionMode="Multiple"
SelectionChanged="CategoryView_SelectionChanged">
<CollectionView.Footer>
<Button
HeightRequest="120"
BackgroundColor="Transparent"/>
</CollectionView.Footer>
<CollectionView.ItemsLayout>
<GridItemsLayout Orientation="Vertical" Span="2" VerticalItemSpacing="1" HorizontalItemSpacing="4"/>
</CollectionView.ItemsLayout>
<CollectionView.ItemTemplate>
<DataTemplate>
<Grid BackgroundColor="{Binding myBackGroundColor}">
<Grid.RowDefinitions>
<RowDefinition Height="36"/>
<RowDefinition Height="33"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="30"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Image Grid.Row="0" Grid.RowSpan="2" Grid.Column="0" Grid.ColumnSpan="2" Source="{Binding Image}"/>
<Label Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2" Text="{Binding Titolo}" FontSize="19" FontAttributes="Bold" TextColor="White" Margin="13,0,0,0"/>
<Image Grid.Row="0" Grid.Column="0" Source="checked.png" IsVisible="{Binding Vis}" Margin="13,5,0,0"/>
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
c#
private async void CategoryView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var selected = e.CurrentSelection;
ClassCategory model = e.CurrentSelection.FirstOrDefault() as ClassCategory;
WebClient clientw = new WebClient();
clientw.Credentials = new NetworkCredential("account", "password");
string Frasi1 = "ftp://epiz_27426656@ftpupload.net/htdocs/" + "Obiettivo" + ".json";
string contents1 = await clientw.DownloadStringTaskAsync(Frasi1);
ObservableCollection<FraseClass> FrasiJsonOnline1 = JsonConvert.DeserializeObject<ObservableCollection<FraseClass>>(contents1);
Frasi.ItemsSource = FrasiJsonOnline1;
ViewFrasi.IsVisible = true;
model.myBackGroundColor = Color.Transparent;
model.Vis = true;
list.Clear();
foreach (ClassCategory cat in selected)
{
list.Add(cat.Titolo);
}
}
【问题讨论】:
-
if (e.CurrentSelection == null) return; -
我的应用程序的制作方式永远不会为空。我希望仅在选择其他项目而不是在页面启动时读取该事件
-
然后在页面加载后分配事件处理程序
-
默认情况下,CollectionView 选择被禁用。在您选择该项目之前,它不会触发
SelectionChanged事件。我使用您提供的 xaml 进行测试。在我选择该项目之前,它不会触发该事件。你能提供更多关于这方面的信息吗? -
我认为问题是因为我在进入该页面时对 CollectionView 的某些元素进行了预选,然后触发了 SelectionChanged。我该如何避免呢?
标签: c# xaml xamarin.forms collectionview