我正在嘗試將專案添加到系結到 ListView 的 ObservableCollection。
定義:
public ObservableCollection<Category> SearchCategoriesResults { get; set; } = new();
XAML
<ListView ItemsSource="{Binding SearchCategoriesResults}"
BackgroundColor="{StaticResource Primary}"
SeparatorVisibility="None"
WidthRequest="250"
RowHeight="30"
HeightRequest="150">
<ListView.ItemTemplate>
<DataTemplate x:DataType="model:Category">
<Label Text="{Binding Name}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
在 try/catch 塊中我得到例外“指定的轉換無效”
public void SearchCategories()
{
SearchCategoriesResults.Clear();
try
{
//Trying arbitrary data
SearchCategoriesResults.Add(new Category { Id = 15, Name = "Name" });
}
catch(Exception ex)
{
//Specified cast is not valid
Debug.WriteLine(ex.Message);
}
}
如果我從我的應用程式的不同區域復制 CollectionView,它作業正常:
<CollectionView ItemsSource="{Binding SearchCategoriesResults}"
SelectionMode="Single"
SelectedItem="{Binding SearchCategoriesSelectedResult, Mode=TwoWay}"
HeightRequest="120"
WidthRequest="250">
<CollectionView.EmptyView>
<StackLayout Padding="50">
<Label TextColor="White"
FontAttributes="Bold"
HorizontalOptions="CenterAndExpand"
Text="NO DATA"
VerticalOptions="CenterAndExpand" />
</StackLayout>
</CollectionView.EmptyView>
<CollectionView.ItemsLayout>
<LinearItemsLayout Orientation="Vertical" />
</CollectionView.ItemsLayout>
<CollectionView.ItemTemplate>
<DataTemplate x:DataType="model:Category">
<Grid HeightRequest="40"
Margin="5,3,5,3"
Padding="5,0,5,0"
ColumnDefinitions="*"
RowDefinitions="*,*"
BackgroundColor="{StaticResource Secondary}">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup Name="CommonStates">
<VisualState Name="Selected">
<VisualState.Setters>
<Setter Property="BackgroundColor" Value="{StaticResource Fourth}" />
</VisualState.Setters>
</VisualState>
<VisualState Name="Normal">
<VisualState.Setters>
<Setter Property="BackgroundColor" Value="{StaticResource Secondary}" />
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Label Grid.Row="0" TextColor="White" Text="{Binding Name}" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" />
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
我不確定為什么 CollectionView 可以作業而 ListView 不能。有人有想法么?
uj5u.com熱心網友回復:
ListView 需要一個ViewCell. (CollectionView 沒有。)嘗試:
<ListView.ItemTemplate>
<DataTemplate x:DataType="model:Category">
<ViewCell>
<Label Text="{Binding Name}" />
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/534412.html
標籤:C#例外数据绑定毛伊岛
上一篇:Pythonexcel資料集轉換
