【问题标题】:Xamarin Databinding and Updating the UIXamarin 数据绑定和更新 UI
【发布时间】:2018-01-14 13:33:41
【问题描述】:

您好,当 Xamarin 表单中的模型发生更改时,我正在努力更新 UI。

为了简单起见,我有几个页面 - 一个显示当前配置文件的 ProfilePage 和一个 Edit Profile Page,其中包含一个包含配置文件属性的列表,单击时可以对其进行编辑。

我认为这是将页面和控件绑定到模型的情况,然后当该模型发生更改时,UI 应该反映这一点,但似乎并非如此。

我遇到的问题是当我对模型进行更改时 UI 没有自动更新。我需要刷新或重新加载,因此我将加载代码放在页面的 OnAppearing 方法中,这显然是不正确的。

我有一个 Profile 类:

public class Profile
{
   public string Name {get; set;}
   public string About {get; set;} 
}

个人资料页面代码隐藏

protected override void OnAppearing()
{
    var p = await getGetDataFromWebservice;
    BindingContext = p;
}

public async void EditPage
{
  EditProfilePage editProfilePage = new EditProfilePage();
  editProfilePage.BindingContext = p;
  Navigation.PushAsync(editProfilePage)
 }

个人资料页 XAML

<Label Text="{Binding Name, }"></Label>
<Label Text="{Binding About, }"></Label>

对于我的编辑个人资料页面,我不确定如何将个人资料属性放入列表中,因此我创建了一个新类来保存它并根据个人资料项填充它

个人资料项目:

public class ProfileItem
{
   public string Name {get;set;}
   public string Value {get;set;}
}

EditProfilePage 代码隐藏:

ObservableCollection<ProfileItem> items = new ObservableCollection<ProfileItem>()

protected override void OnAppearing()
{
   p = (Profile)BindingContext;
   items.clear();
   items.Add( (new ProfileItem {Name = "Name", Value=p.Name.ToString() }));
   items.Add( (new ProfileItem {Name = "About", Value = p.About.ToString() }))

    list_Profile_Details.ItemsSource = items;

}

EditProfile XAML:

<ListView x:Name="list_Profile_Details" HeightRequest="500" RowHeight="45">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <TextCell Text="{Binding Name, Mode=TwoWay}"  Detail="{Binding Value, }"   />

                </DataTemplate>
            </ListView.ItemTemplate>
    </ListView>    

这些似乎反映了更新,但这不是正确的做法,希望得到一些指导。

谢谢。

【问题讨论】:

  • 阅读INotifyPropertyChanged

标签: c# xaml xamarin data-binding xamarin.forms


【解决方案1】:

“问题”的解决方案是查看 MVVM 模式。首先,我建议您查看“带有 Xamarin.Forms 的 MVVM”的官方文档,您可以找到它herehere

阅读这些文档后,您将看到在 Xamarin.Forms 项目中执行 MVVM 和数据绑定的更好方法,第一步是将数据绑定的逻辑与代码隐藏类分开并包含在您的项目中使用ViewModels

使用INotifyPropertyChanged 接口和PropertyChangedEventHandler 实现更改模型状态时更新用户界面的最佳方式。

我的博客 here 上有几篇关于 MVVM 和 XF 的博文和代码示例,我的一篇关于简单 mvvm 的博文是 here

还有一些适用于 Xamarin.Forms 的出色 MVVM 框架,您可能希望稍后在掌握“普通”MVVM 时看到这些框架。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多