如何解决Xamarin MVVM 数据绑定通过 ViewModel 同时具有包含对象列表的类
我的问题是我有一个 Location 类,LocationsDb 类,在 LocationsDb 中,我有一个包含硬编码数据的公共列表。现在我在尝试从 LocationsDb 类中的 List 绑定数据时遇到了 viewmodel 类的问题。我希望我的 Listview 只显示城市。我的代码做错了什么?
位置类
public class Location
{
public string city { get; set; }
public string street { get; set; }
public int emptySpaces { get; set; }
public Location(string city,string street,int emptySpaces)
{
this.city = city;
this.street = street;
this.emptySpaces = emptySpaces;
}
}
LocationsDb 类
public class LocationsDb
{
public List<Location> Locations = new List<Location>
{
new Location("Vilnius","Ateities g. 91",5),new Location("Vilnius","S. Nėries g. 91",10),"Lukiškių g. 6",1),"Dominikonų g. 4",0),new Location("Kaunas","Jonavos g. 1",8),"Vytauto pr. 24",3),"Žemaičių g. 31B",new Location("Klaipėda","Smiltelės g. 2A",13),"Žvejų g. 27",7),"Minijos g. 90","Bangų g. 5",};
public List<Location> GetLocations()
{
return this.Locations;
}
}
viewmodel 类
public class MainPageviewmodel
{
public ObservableCollection<Location> AllCities { get; set; }
public ObservableCollection<Location> allCities { get { return AllCities; } }
public MainPageviewmodel()
{
AllCities = new ObservableCollection<Location>(new LocationsDb().Locations);
}
}
XML
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="ParkingApp.Views.MainPage"
ControlTemplate="{StaticResource MyTemplate}"
>
<ContentPage.Content>
<Grid>
<Grid.RowDeFinitions>
<RowDeFinition Height="auto"/>
<RowDeFinition Height="auto"/>
</Grid.RowDeFinitions>
<Label Grid.Row="0" Text="Select City"
BackgroundColor="#e8e8e8" HorizontalTextAlignment="Center"
HeightRequest="50" VerticalTextAlignment="Center"
FontSize="30"/>
<ListView x:Name="CitiesListview" Grid.Row="1" ItemsSource="{Binding AllCities}" SeparatorColor="Black">
<ListView.ItemTemplate>
<DataTemplate>
<TextCell TextColor="Black" Text="{Binding city}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</ContentPage.Content>
解决方法
我使用您的代码将 observablecollection 绑定到 ListView,没有问题。我没有更改 ContentPage.xaml 的任何代码
请检查我的 ContentPage.cs:
public partial class Page8 : ContentPage
{
public Page8()
{
InitializeComponent();
this.BindingContext = new MainPageViewModel();
}
}
public class MainPageViewModel
{
public ObservableCollection<Location> AllCities { get; set; }
public MainPageViewModel()
{
AllCities = new ObservableCollection<Location>(new LocationsDb().Locations);
}
}
关于ListView绑定,请看:
https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/listview/data-and-databinding
,我不知道出了什么问题,但下次我启动我的应用程序时,它就像一个魅力。我的代码没有变化。所以我不知道,也许是某种绑定延迟或错误,但代码很好,我的列表视图显示了我想要的内容。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。