Xamarin 窗体中的列表视图数据绑定



在登录或导航到任何页面,从API获取数据时,我正在使用一个额外的按钮(显示社区)来获取我的数据。 这是我的代码

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:viewModels="clr-namespace:epolleasy.ViewModels;assembly=epolleasy"
x:Class="epolleasy.Views.DpCommunities">
<ContentPage.BindingContext>
<viewModels:DashboardViewModel />
</ContentPage.BindingContext>

<StackLayout>
<Button Command="{Binding GetDashboard}" Text="Show Communities"/>
<ListView ItemsSource="{Binding UserDashboard.Com}"
HasUnevenRows="True">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout>
<Label Text="{Binding CommunityName}"/>
<Label Text="{Binding CommunityUsers.Count}"/>
<Label Text="{Binding FormsCommunity.Count}"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>

</ContentPage>

这是我的视图模型中的 GetDashboard命令

public ICommand GetDashboard
{
get
{
return new Command(async () =>
{
var accessToken = Settings.AccessToken;
UserDashboard = await _apiServices.GetDashboard(accessToken);
});
}

}

这是我在同一视图模型中的用户仪表板

public Dashboard UserDashboard
{
get { return _userDashboard; }
set
{
_userDashboard = value;
OnPropertyChanged();
}
} 

我想摆脱那个额外的按钮

在 OnAppearing 方法中获取数据

void async override OnAppearing() 
{
// call VM GetData method
}

正如我从这些小代码片段中看到的那样,为您提供了什么以及我可以得出的结论......您正在将列表视图绑定到某些ListObservableCollection,并且当命令被"触发"(单击按钮时)时,您正在调用 WebApi。

删除按钮的使用:您可以在调用 Web API 的地方使用该代码,并且可以将其放入 ViewModel 构造函数中,因此在这种情况下,您可以简化它,Web API 将在创建 ViewModel 时自动调用,并且将填充您的ListObservableCollection, 如果您以正确的方式"尊重"MVVM,那么您的ListView将使用来自 API 的数据正确更新。


这是我的观点,这种方法会奏效,社区的问题是:">这样做是一种好的做法吗?...但正如我所说,这将对你有用,你不需要那个Button.

附言下次包括所有相关的类,而不仅仅是小方法,当您包含所有代码时,我们可以看到您的情况,我们可以为您提供帮助

最新更新