我在Xamarin Forms项目中似乎遇到了数据绑定问题。我有两个视图:一个用于列出项目,另一个用于查看详情。
列表视图可以很好地加载项目列表及其所有属性,但详细页面是空白的,无法绑定属性。
列表的视图模型大致如下:
再次测试成功了。 但是详细视图看起来像这样:
页面完全空白。我需要在ItemModel中添加INotifyPropertyChanged吗?如果是,我不明白为什么,因为ListView在没有任何这样的需求的情况下绑定了相同的模型,那么为什么普通标签不能绑定呢?我做错了什么?
列表视图可以很好地加载项目列表及其所有属性,但详细页面是空白的,无法绑定属性。
列表的视图模型大致如下:
public class MainPageViewModel : ViewModelBase
{
public MainPageViewModel(IItemService itemService) : base(itemService) { }
public ObservableCollection<ItemModel> Items { get; set; } = new ObservableCollection<ItemModel>();
public async override void Start()
{
base.Start();
Items.Clear();
var results = await service.GetItems();
foreach (var result in results)
{
Items.Add(result);
}
IsLoading = false;
}
}
这段代码与以下的XAML绑定:
<ListView x:Name="ItemListView" ItemsSource="{Binding Items}" ItemSelected="ItemListView_ItemSelected">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<StackLayout Orientation="Vertical">
<Image Source="{Binding Image}" />
</StackLayout>
<StackLayout Orientation="Vertical" Grid.Column="1">
<Label Text="{Binding Name}" />
<Label Text="{Binding Description}" />
</StackLayout>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
再次测试成功了。 但是详细视图看起来像这样:
public class DetailsPageViewModel : ViewModelBase
{
public DetailsPageViewModel(IItemService itemService) : base(itemService) { }
private ItemModel item;
public ItemModel Item
{
get { return item; }
set
{
item = value;
RaisePropertyChanged();
}
}
protected string ItemId { get; set; }
public void Init(string itemId)
{
this.ItemId = itemId;
}
public async override void Start()
{
base.Start();
Item = await service.GetItem(ItemId);
IsLoading = false;
}
}
我正在尝试将ItemModel属性绑定到详细视图上的标签:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MvvmCrossFormsDemo.Views.DetailsPageView">
<StackLayout>
<Label Text="{Binding Item.Name}" />
<Image Source="{Binding Item.Image}" />
</StackLayout>
</ContentPage>
页面完全空白。我需要在ItemModel中添加INotifyPropertyChanged吗?如果是,我不明白为什么,因为ListView在没有任何这样的需求的情况下绑定了相同的模型,那么为什么普通标签不能绑定呢?我做错了什么?