【发布时间】:2020-08-13 14:02:09
【问题描述】:
我在使用 collectionview 时遇到问题,我正在尝试让绑定工作。 正如我在其他帖子中看到的那样,我试图通过设置所涉及的每个元素的 miniumheight 和 heightrequest 来设置高度,但没有成功。我有一个带有文本单元的列表视图,这是我可以让它工作的唯一方法。
型号
[Table("Category")]
public class Category
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string Name { get; set; }
}
视图模型
public class CategoriesViewModel : BaseViewModel
{
public ObservableCollection<Category> Categories { get; }
public Command LoadCategoriesCommand { get; }
public Command AddCategoryCommand { get; }
public CategoriesViewModel()
{
Title = "Categories";
Categories = new ObservableCollection<Category>();
LoadCategoriesCommand = new Command(async () => await ExecuteLoadCategoriesCommand());
AddCategoryCommand = new Command(OnAddCategory);
}
async Task ExecuteLoadCategoriesCommand()
{
IsBusy = true;
try
{
Categories.Clear();
var categories = await DataStore.GetCategoriesAsync();
foreach (var cat in categories)
{
Categories.Add(cat);
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
Debug.WriteLine(ex.Message);
}
finally
{
IsBusy = false;
}
}
public void OnAppearing()
{
IsBusy = true;
}
查看
xmlns:local="clr-namespace:FreeScanner.ViewModels"
xmlns:model="clr-namespace:FreeScanner.Models"
x:Name="BrowseCategoriesPage">
<ContentPage.ToolbarItems>
<ToolbarItem Text="Add" Command="{Binding AddCategoryCommand}" />
</ContentPage.ToolbarItems>
<RefreshView x:DataType="local:CategoriesViewModel" Command="{Binding LoadCategoriesCommand}"
IsRefreshing="{Binding IsBusy, Mode=TwoWay}">
<CollectionView x:Name="CategoriesListView"
ItemsSource="{Binding Categories}">
<CollectionView.ItemTemplate>
<DataTemplate>
<Grid Padding="10" x:DataType="model:Category">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Label Grid.Column="1"
Grid.Row="1"
Text="{Binding Name}"
FontAttributes="Bold" />
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
<!--<ListView ItemsSource="{Binding Categories}"
x:Name="CategoriesListView"
SelectionMode="None"
RowHeight="50">
<ListView.ItemTemplate>
<DataTemplate x:DataType="model:Category">
<TextCell Text="{Binding Name}"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>-->
</RefreshView>
当我调试并将鼠标悬停在 CollectView ItemSource 类别上时,我确实看到了 Count = 1,我可以验证它是否从数据库中正确加载。
【问题讨论】:
-
如果 ListView 工作,它可能不是绑定问题。布局引擎更有可能无法确定您的布局需要多大的尺寸。您可以通过在 Label 中硬编码一个值来轻松测试它以查看它是否显示。
-
在视图中使用数据库模型不是一个好主意。
-
是的,我根据您在另一个线程上的评论做到了。我希望看到它打印 HC 值乘以计数,但没有显示。
-
@neil 新文档推荐它。现在是选项卡式项目中新项目附带的代码
-
哪个文档推荐它?这不应该是 MVVM,而不是 DBVVM。如果您更新 Category.Name,您的视图将不会更新,因为您的数据库类不支持 INotifyPropertyChanged。
标签: c# user-interface xamarin.forms observablecollection