【发布时间】:2020-04-22 00:58:05
【问题描述】:
以下 Xamarin Forms 应用包含一个 Picker 和一个 CollectionView 控件绑定到相同的动物 List(Chicken 和 Cow)。当我按下升级按钮时,动物应该升级到Eagle 和Elephant。动物已升级,但 Picker 并未反映更改。 CollectionView 工作正常。
我在这里做错了什么?如果需要,可以找到该项目的源代码at Github。
点击查看演示
MainPage.xaml
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="SampleApp.MainPage">
<StackLayout Margin="0,100,0,0">
<Button Text="Upgrade Animals"
Margin="10"
HorizontalOptions="Center"
VerticalOptions="Start"
Command="{Binding Upgrade}" />
<Picker ItemsSource="{Binding Animals}" />
<CollectionView ItemsSource="{Binding Animals}" />
</StackLayout>
</ContentPage>
MainPageModel.cs
public class MainPageModel : INotifyPropertyChanged
{
public MainPageModel()
{
_Animals = new List<string>() { "Chicken", "Cow" };
}
private List<string> _Animals;
public List<string> Animals
{
get { return _Animals; }
set
{
_Animals = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Animals"));
}
}
public Command Upgrade
{
get
{
return new Command(_ =>
{
Animals = new List<string>() { "Eagle", "Elephant" };
});
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
更新
以上代码正在运行 XF 4.3.0.908675。我降级到 4.2.0.778463,问题就消失了。这可能是最新 XF 版本中引入的新错误。
【问题讨论】:
-
诚然是一种解决方法,但您可以手动清除并将新项目重新添加到选择器
-
谢谢,实际上我已经尝试过了。同样的问题。 CollectionView 更新正常。选择器没有。
-
你的意思是你从代码中的选择器中删除了项目并且项目仍然存在?
-
Picker 和 CollectionView 都绑定到同一个列表。在上面的示例中,我创建了一个新列表,但我尝试了 Animals.Clear() 然后一一添加。两种方法都有相同的问题。我更新了答案,但这似乎是一个 XF 错误。我降级到 4.2.0.778463,问题就消失了。
-
出于好奇,您是否启用了热重载?我有最新的 xf,选择器工作正常
标签: xamarin xamarin.forms