我正试图利用CollectionView中的自定义控件,并希望将特定CollectionView ItemTemplate的整个对象传递到我的自定义控件中。
这是我的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:未找到"的属性、BindableProperty或事件;Op";,或值和属性之间的类型不匹配。
我尝试的是可能的吗?
是的,这是可能的。现在的情况是,xaml没有试图弄清楚{Binding .}
的类型是WorkOp
。它需要类型为object
的属性。
修复方法是给它一个类型为object
的属性。然后,为了方便在自定义控件中进行访问,请创建第二个属性,将其强制转换为WorkOp
:
public static readonly BindableProperty WorkOpProperty =
BindableProperty.Create(nameof(Op), typeof(object), typeof(ContentPage));
public object Op
{
get { return GetValue(WorkOpProperty); }
set { SetValue(WorkOpProperty, value); }
}
private WorkOp TypedOp => (WorkOp)Op;
注意:将上面的Op
和TypedOp
更改为您喜欢的任何名称。如果您更改Op
,请记住也要更改引用它的xaml。