.NET MAUI弹窗中CollectionView简单绑定失效问题
.NET MAUI Popup中CollectionView列表项属性绑定失败问题
在.NET MAUI的Popup弹窗中添加CollectionView并进行数据绑定时,遇到列表项属性无法识别的问题:绑定Label的Text属性为{Binding PersonName}时,出现错误提示:
Binding: Property 'PersonName' not found on 'BindingTest.Views.PupupPage'
若将绑定改为{Binding .},则无错误且显示模型类名称,说明绑定引擎在查找PopupPage的属性,而非CollectionView的ItemsSource对应的模型属性。
问题代码
XAML页面代码
<toolkit:Popup xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit" xmlns:view ="clr-namespace:BindingTest.Views" x:DataType="view:PupupPage" x:Class="BindingTest.Views.PupupPage"> <Border x:Name="popupBorder" BackgroundColor = "LightGrey" Stroke ="Black" StrokeThickness = "2"> <Border.StrokeShape> <RoundRectangle CornerRadius="15" /> </Border.StrokeShape> <Border.Shadow> <Shadow Brush="Gray" Offset="5,5" Radius="5" Opacity="0.8" /> </Border.Shadow> <Grid RowDefinitions="*,Auto"> <CollectionView x:Name="personsList" Grid.Row="0" SelectionMode="Single"> <CollectionView.ItemsLayout> <LinearItemsLayout Orientation="Vertical" ItemSpacing="5" /> </CollectionView.ItemsLayout> <CollectionView.ItemTemplate> <DataTemplate> <Grid ColumnDefinitions="Auto,*,Auto"> <Label Text="{Binding PersonName}"/> </Grid> </DataTemplate> </CollectionView.ItemTemplate> </CollectionView> </Grid> </Border> </toolkit:Popup>
后台C#代码
using CommunityToolkit.Maui.Views; namespace BindingTest.Views; public partial class PupupPage : Popup { public class SimpleModel { public string ImageURL { get; set; } public string PersonName { get; set; } public string PersonEmail { get; set; } public RadioButton PersonSelected { get; set; } } public List<SimpleModel> simpleModels = new(); public PupupPage() { InitializeComponent(); BindingContext = this; PopulateList(); } public void PopulateList() { SimpleModel person = new SimpleModel() { PersonName = "Person Name"}; simpleModels.Add(person); personsList.ItemsSource = simpleModels; } }
问题原因
Popup页面设置了x:DataType="view:PupupPage",开启了编译时绑定检查,而DataTemplate未指定自身的x:DataType,导致它继承了父级(PopupPage)的DataType,绑定引擎会在PopupPage类中查找PersonName属性,自然无法找到。
解决方案
方案1:为DataTemplate指定DataType
在XAML中添加SimpleModel的命名空间引用(由于SimpleModel嵌套在PupupPage中,命名空间为BindingTest.Views),然后给DataTemplate设置x:DataType:
- 在Popup的根标签中添加命名空间:
xmlns:local="clr-namespace:BindingTest.Views"
- 修改
DataTemplate标签:
<DataTemplate x:DataType="local:PupupPage+SimpleModel"> <Grid ColumnDefinitions="Auto,*,Auto"> <Label Text="{Binding PersonName}"/> </Grid> </DataTemplate>
方案2:移除Popup的x:DataType
如果不需要编译时绑定检查,可以直接移除Popup根标签中的x:DataType="view:PupupPage",绑定会回退到运行时模式,自动识别ItemsSource对应的模型属性。
额外优化建议
- 将后台的
simpleModels字段改为ObservableCollection类型的公共属性 ,这样数据更新时UI会自动刷新:
public ObservableCollection<SimpleModel> SimpleModels { get; set; } = new();
- 后续可以通过XAML绑定ItemsSource:
ItemsSource="{Binding SimpleModels}",而非后台直接赋值,更符合MVVM规范。
内容的提问来源于stack exchange,提问作者Glenn Taylor
相关产品推荐
相关产品推荐

