【发布时间】:2022-01-22 10:24:32
【问题描述】:
我有这些看法:
<StackLayout Orientation="Vertical" Padding="30,24,30,24" Spacing="10">
<syncfusion:SfListView x:Name="listView" ItemsSource="{Binding Items}">
<syncfusion:SfListView.ItemTemplate>
<DataTemplate>
<StackLayout>
<Label Text="{Binding Text}"/>
</StackLayout>
</DataTemplate>
</syncfusion:SfListView.ItemTemplate>
</syncfusion:SfListView>
它是 C# 代码:
public partial class ItemsPage : ContentPage
{
ItemsViewModel _viewModel;
public ItemsPage()
{
InitializeComponent();
BindingContext = _viewModel = new ItemsViewModel();
}
protected override void OnAppearing()
{
base.OnAppearing();
_viewModel.OnAppearing();
}
}
这里是模型:
public class Item
{
public string Id { get; set; }
public string Text { get; set; }
public string Description { get; set; }
}
我不知道为什么,但使用这个视图模型:
public class ItemsViewModel : BaseViewModel
{
private Item _selectedItem;
public ObservableCollection<Item> Items { get; }
public Command LoadItemsCommand { get; }
public Command AddItemCommand { get; }
public Command<Item> ItemTapped { get; }
public ItemsViewModel()
{
Title = "Contacts by David Zomada";
Items = new ObservableCollection<Item>();
LoadItemsCommand = new Command(async () => await ExecuteLoadItemsCommand());
ItemTapped = new Command<Item>(OnItemSelected);
AddItemCommand = new Command(OnAddItem);
}
async Task ExecuteLoadItemsCommand()
{
IsBusy = true;
try
{
Items.Clear();
var items = await DataStore.GetItemsAsync(true);
foreach (var item in items)
{
Items.Add(item);
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
finally
{
IsBusy = false;
}
}
public void OnAppearing()
{
IsBusy = true;
SelectedItem = null;
}
public Item SelectedItem
{
get => _selectedItem;
set
{
SetProperty(ref _selectedItem, value);
OnItemSelected(value);
}
}
private async void OnAddItem(object obj)
{
await Shell.Current.GoToAsync(nameof(NewItemPage));
}
async void OnItemSelected(Item item)
{
if (item == null)
return;
// This will push the ItemDetailPage onto the navigation stack
await Shell.Current.GoToAsync($"{nameof(ItemDetailPage)}?{nameof(ItemDetailViewModel.ItemId)}={item.Id}");
}
}
编译器说:“绑定:在“Contacts.ViewModels.ItemsViewModel”上找不到属性“Text”。(XFC0045)”
我显然错了,但我不明白我的错误在哪里?你能帮我理解为什么我的视图没有正确绑定到视图模型吗?
到目前为止,我的理解是,如果在使用绑定绑定数据模板上的属性时将项目源绑定到集合视图,则数据会从项目源获取数据。
【问题讨论】:
-
您没有在任何地方设置
Text。以你自己的代码为例。您将标题设置为某事。然后你将你的标题绑定到你在 XAML 中的标题。您没有对您的文本执行此操作。 -
是的,它在视图中 ´´ 抱歉我忘记添加模型了
-
标题是在基本模型上定义的,也是 INotifyPropertyChanged
-
根据模型和视图模型绑定应该是
Items.Text。试试看。 -
它说的一样。看起来它试图在视图模型上查找项目或项目属性,而不是理解它必须在自己的项目源上查找它
标签: c# xamarin model-view-controller