我在一个用户可以发布Feed更新的屏幕上,此Feed更新包含文本和一些附加文件 . 我的xaml视图基本上是 StackLayout
,其中包含 ListView
和 Editor
以及几个 Buttons
. 问题是我正在尝试在 onAppearing
方法中设置我的 ListView
的 ItemSource
. 该方法被称为正常 . 我正在设置的集合按预期更改 . 但由于某种原因, ListView
没有更新 . 在设置 Source
调用 Editor
焦点方法后,使 ListView
正常工作的解决方法正确 . 我这样做是因为我发现当我在设置集合后点击编辑器时, ListView
正确呈现 . 但这是一个非常讨厌的解决方法 .
这是我的xaml:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="HalliganTL.View.UpdateFeedPage">
<StackLayout Orientation="Vertical" >
<ListView x:Name="AttachedFilesListView" MinimumHeightRequest="50" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" >
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout HorizontalOptions="StartAndExpand" Orientation="Horizontal">
<Button Text="[X]" />
<StackLayout Padding="5,0,0,0" VerticalOptions="StartAndExpand" Orientation="Vertical">
<Label Text="{Binding Name}" VerticalTextAlignment="Center" FontSize="Medium" />
</StackLayout>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Editor x:Name="UpdateFeedEditor" FontSize="15" Text="{Binding PostText}" VerticalOptions="FillAndExpand" />
<Button Text="Attach file" TextColor="White" BackgroundColor="#77D065" Clicked="onAttachFileClicked"/>
<Button Text="Post" TextColor="White" BackgroundColor="#77D065" Clicked="onPostClicked"/>
</StackLayout>
</ContentPage>
这是我的页面代码:
public partial class UpdateFeedPage : ContentPage
{
public static List<FileObject> CurrentSelectedFile = new List<FileObject>();
public static string PostText = "";
public UpdateFeedPage()
{
InitializeComponent();
Title = "New Update";
UpdateFeedEditor.Text = PostText;
}
protected override void OnAppearing()
{
AttachedFilesListView.ItemsSource = CurrentSelectedFile;
UpdateFeedEditor.Focus();
base.OnAppearing();
}
async void onPostClicked(object sender, EventArgs e)
{
await Navigation.PopAsync();
}
async void onAttachFileClicked(object sender, EventArgs e)
{
await Navigation.PushAsync(new FilePickerPage());
}
}
我玩了很多东西,比如:
-
从ListView和包含ListView的StackLayout更改HorizontalOptions和VerticalOptions .
-
删除了除StackLayout和子ListView之外的所有其他控件 .
但到目前为止没有任何工作,除了以编程方式调用编辑器,Focus方法
NOTE:
正如您所看到的,我设置的ListView集合是静态的,我直接从另一个页面修改该集合,但我认为这没关系,因为当我在OnAppearing中设置断点时,正在正确地修改集合 .
1 回答
解决该刷新问题的两种方法 .
1st way)
通过重置
ItemsSource
强制ListView从List<FileObject>
集合刷新:Current:
Change to:
2nd way)
将
List<FileObject>
集合替换为ObservableCollection<FileObject>
,以便通过ListView
将要侦听的NotifyCollectionChangedAction.Add|Remove|...
事件发布更改 .Current:
Change to:
注意:还要添加
using System.Collections.ObjectModel;
你的
OnAppearing
成了: