【问题标题】:ListView Data Binding in Xamarin FormsXamarin 表单中的 ListView 数据绑定
【发布时间】:2017-06-20 08:24:16
【问题描述】:

在登录或导航到任何页面,从 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>

这是我的 ViewModel 中的 GetDashboard 命令

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

}

这是我在同一视图模型中的 UserDashboard

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

我想去掉那个额外的按钮

【问题讨论】:

    标签: xamarin xamarin.forms


    【解决方案1】:

    在 OnAppearing 方法中获取数据

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

    【讨论】:

    • 是的,或者只是将相同的代码公开为公共方法
    • 不工作,我想我没有正确理解。你能多写点 OnAppearing() 方法吗?
    • 你把它放在你的页面吗?你确认它被调用了吗?仅仅说“不工作”并不是很有帮助的信息。
    • 我没有得到你的答案。
    • 我问了你几个问题,你都没有回答。
    【解决方案2】:

    正如我从这些小代码 sn-ps 中看到的那样,我可以得出结论......你正在将 ListView 绑定到一些 ListObservableCollection,并且当 Command 被“触发”时(在按钮单击)您正在调用 WebApi。

    要删除按钮的使用:您可以在调用 web api 的地方使用该代码,并且可以将其放在 ViewModel 构造函数中,这样在这种情况下,您可以轻松实现 Web Api 将在创建您的 ViewModel 时自动调用,并且您的 ListObservableCollection 将被填充,如果您以正确的方式“尊重”MVVM,您的 ListView 将使用来自 api 的数据正确更新。


    这是我的意见,这种方法会奏效,社区的问题是:“这样做是一种好习惯吗?”......但正如我所说,这对你有用,你会不需要那个Button

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

    【讨论】:

      猜你喜欢
      • 2016-09-08
      • 1970-01-01
      • 2016-10-10
      • 1970-01-01
      • 2018-10-19
      • 2018-08-14
      • 2016-06-26
      • 2018-09-25
      • 1970-01-01
      相关资源
      最近更新 更多