【发布时间】:2021-10-12 13:39:45
【问题描述】:
我正在尝试将我的 listView(其中包含多个绑定对象和用户条目作为输入)写入文本文件。 我想出了将其序列化为 Json 的想法,然后单击按钮将其写入文本(我是新来的 :))。但是我经常遇到 Json Loops 错误。
我的listView的名字是LL:
private void Save_Clicked(object sender, EventArgs e)
{
string Listi = JsonConvert.SerializeObject(LL);
File.WriteAllText(DailyTex, Listi);
editor.Text = File.ReadAllText(DailyTex);
DisplayAlert("Save completed", "Please Try Egain", "Continue");
}
错误是:
Newtonsoft.Json.JsonSerializationException:“检测到类型为“Xamarin.Forms.Grid”的属性“ParentView”的自引用循环。路径 'TemplatedItems[0].View.Children[0]'.'
我的 Xaml 页面
<ListView x:Name="LL" Grid.Row="3" ItemsSource="{Binding energy}" HeightRequest="300" >
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid Padding="5" BackgroundColor="White" RowSpacing="40" >
<Grid.RowDefinitions>
<RowDefinition Height="50"></RowDefinition>
<RowDefinition Height="50"></RowDefinition>
</Grid.RowDefinitions>
<Label x:Name="label" HorizontalOptions="Center" Text="{Binding EE}" FontSize="18" TextColor="Black" Grid.Column="0" Grid.Row="0" />
<Entry TextChanged="Entry_TextChanged" HorizontalOptions="Center" VerticalOptions="Center" Keyboard="Numeric" Placeholder=". . . . . . . ." Grid.Column="1" Grid.Row="0" BackgroundColor="Beige" WidthRequest="80" />
<Entry TextChanged="Entry_TextChanged_1" HorizontalOptions="Center" VerticalOptions="Center" Keyboard="Numeric" Placeholder=". . . . . . . ." Grid.Column="2" Grid.Row="0" BackgroundColor="Beige" WidthRequest="80"/>
<Entry TextChanged="Entry_TextChanged_2" HorizontalOptions="Center" VerticalOptions="Center" Keyboard="Numeric" Placeholder=". . . . . . . ." Grid.Column="3" Grid.Row="0" BackgroundColor="Beige" WidthRequest="80"/>
<BoxView Grid.Column="0" Grid.Row="0" BackgroundColor="Black" WidthRequest="1" HorizontalOptions="EndAndExpand" VerticalOptions="FillAndExpand"/>
<BoxView Grid.Column="1" Grid.Row="0" BackgroundColor="Black" WidthRequest="1" HorizontalOptions="EndAndExpand" VerticalOptions="FillAndExpand"/>
<BoxView Grid.Column="2" Grid.Row="0" BackgroundColor="Black" WidthRequest="1" HorizontalOptions="EndAndExpand" VerticalOptions="FillAndExpand"/>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
【问题讨论】:
-
ListView 是一个复杂的 UI 对象。你不能像那样序列化它。您需要序列化作为 ListvView 的 ItemsSource 的数据对象
-
没有 NuGet 来完成这项工作吗?
-
是的,Newtonsoft。将您的 ItemSource 序列化为文件将需要两行代码。
-
它有趣的列表视图没有 foreach 语句...
-
@BehzadChangizi - listview 不支持 foreach 并非偶然(或疏忽)。 ListView 是一个复杂的实体,它的工作是使某些东西在视觉上出现。它不打算以您尝试的方式使用。事实上,考虑到不同的平台以及它们的发展方式,很难使这项工作始终如一地工作。不要尝试从列表视图中提取任何内容。相反,从用于创建列表视图的 Source 中获取该信息。这是“视图和模型分离”的一部分。