我正在按照 this 链接将 CollectionView 添加到我的 XAML 页面,但我得到了
绑定:找不到属性“AccountNumber” “***GlAccountsViewModel” .
当我单击
AccountNumber
时,Visual Studio 的智能显示并正确导航,但当我尝试运行该应用程序时,出现此错误。
这是我的代码:
public class GlAccount
{
public string AccountNumber { get; set; }
}
public sealed partial class GlAccountsViewModel : ObservableObject
{
private readonly GlAccountService _glAccountService;
[ObservableProperty] private bool isRefreshing;
[ObservableProperty]
private IEnumerable<GlAccount> _accounts = new List<GlAccount>();
public GlAccountsViewModel(GlAccountService glAccountService)
{
_glAccountService = glAccountService;
}
[RelayCommand]
async Task OnAppearing()
{
await Refresh();
}
[RelayCommand]
async Task Refresh()
{
Accounts = await _glAccountService.GetAllAsync();
IsRefreshing = false;
}
}
xmlns:vm="clr-namespace:MyProjectName.ViewModels.GlAccount"
x:Class="MyProjectName.Pages.GlAccount.GlAccountsPage"
x:TypeArguments="vm:GlAccountsViewModel"
x:DataType="vm:GlAccountsViewModel"
<RefreshView IsRefreshing="{Binding IsRefreshing}"
Command="{Binding RefreshCommand}">
<CollectionView ItemsSource="{Binding Accounts}">
<CollectionView.ItemTemplate>
<DataTemplate>
<Grid Padding="10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Label Text="{Binding AccountNumber}"/>
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</RefreshView>
我尝试过,但没有运气。
private ObservableCollection<GlAccount> _accounts = new ObservableCollection<GlAccount>();
我在这里缺少什么?
这可能与编译的绑定有关。由于您为 ContentPage 设置了
x:DataType="vm:GlAccountsViewModel"
,因此 CollectionView 中每个项目的 BindingContext 都已更改。
所以,我们可以在CollectionView的DataTemplate中重新定义
x:DataType
<CollectionView ItemsSource="{Binding Accounts}">
<CollectionView.ItemTemplate>
<DataTemplate x:DataType="model:GlAccount">
<Grid Padding="10">
<Grid.RowDefinitions>
然后其数据对象的类型被定义为
GlAccount
。这样就可以找到 AccountNumber
属性。
希望有帮助!