.NET MAUI中如何将CollectionView项对象传递给自定义控件?
CollectionView传递完整项到自定义控件的问题解决
问题场景
尝试在CollectionView的ItemTemplate中,将当前绑定的完整WorkOp对象传递给自定义控件TableMeasureView,但编译报错。
页面XAML代码
<CollectionView ItemsSource="{Binding WorkOps}" SelectionMode="None" ItemsLayout="VerticalList"> <CollectionView.ItemTemplate> <DataTemplate> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="75" /> <ColumnDefinition Width="15" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="auto"/> <RowDefinition Height="auto"/> </Grid.RowDefinitions> <Label Grid.Column="0" Text="{Binding OpType}" FontSize="Caption" VerticalTextAlignment="Center"/> <Label Grid.Column="1" Text="{Binding OpNumber}" FontSize="Caption" VerticalTextAlignment="Center"/> <Label Grid.Column="2" Text="{Binding Instructions}" FontSize="Body"/> <Entry Grid.Column="2" Grid.Row="1" Text="{Binding Measure}" IsVisible="{Binding IsSimpleMeasure}" /> <root:TableMeasureView Grid.Column="2" Grid.Row="1" Op="{Binding .}" IsVisible="{Binding IsTableMeasure}" /> </Grid> </DataTemplate> </CollectionView.ItemTemplate> </CollectionView>
自定义控件代码
public class TableMeasureView : Grid { public static readonly BindableProperty WorkOpProperty = BindableProperty.Create(nameof(Op), typeof(WorkOp), typeof(ContentPage)); public WorkOp Op { get { return (WorkOp)GetValue(WorkOpProperty); } set { SetValue(WorkOpProperty, value); } } public TableMeasureView() { } // ... }
编译错误
XamlC错误XFC0009:未找到“Op”对应的属性、可绑定属性或事件,或者值与属性类型不匹配。
错误原因
自定义控件中定义BindableProperty时,ownerType参数指定错误:你将所有者类型写成了typeof(ContentPage),但正确的所有者应该是自定义控件本身typeof(TableMeasureView)。这个错误会导致XAML编译器无法关联Op属性与对应的可绑定属性,从而抛出找不到属性的错误。
修正方案
修改BindableProperty的创建代码,将owner类型改为TableMeasureView:
public class TableMeasureView : Grid { public static readonly BindableProperty WorkOpProperty = BindableProperty.Create(nameof(Op), typeof(WorkOp), typeof(TableMeasureView)); public WorkOp Op { get { return (WorkOp)GetValue(WorkOpProperty); } set { SetValue(WorkOpProperty, value); } } public TableMeasureView() { } // ... }
结论
你尝试的这种实现方式完全可行:通过{Binding .}绑定当前DataContext的完整对象,再通过自定义控件的可绑定属性接收,是CollectionView中传递完整项对象的标准做法。修正上述owner类型错误后,代码即可正常编译运行。
内容的提问来源于stack exchange,提问作者hack3rfx
相关产品推荐
相关产品推荐

