【发布时间】:2020-10-15 04:10:04
【问题描述】:
在我的视图代码中,我创建了一个模型类型的对象。我将该对象添加到 ObservableCollection 并在我的 XAML 代码中绑定到该集合以用于 StackLayout。我在 StackLayout 中放置了一个自定义控件 ContentView。我希望能够使用 ObservableCollection 中的整个对象在控件上设置一个属性。然后,控件将根据对象集的各个部分设置自己的内容。如果这有点令人困惑,让我演示一下我想要做什么。
更新 我已经修改了我的代码,包括 XAML 和 C#,以尝试几种方法来访问源集合中的当前元素,基于 Jason 提供的信息(在 cmets 下方)并使用我在 Binding Declarations Overview 中找到的信息。
这是修改后的 XAML:
<StackLayout BindableLayout.ItemsSource="{Binding IdCardCollection}"
Margin="0, 0, 0, 0" >
<BindableLayout.ItemTemplate>
<DataTemplate>
<StackLayout>
<!-- Content -->
<Frame HeightRequest="360" Margin="17, 0, 16, 0"
BorderColor="{StaticResource NGIC_GrayishWhite}"
HasShadow="True">
<Grid Margin="-10, -13, -10, 5">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="80*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="260*" />
<ColumnDefinition Width="73*" />
</Grid.ColumnDefinitions>
<cardViews:ThreeLineCardView Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2"
Margin="0, 0, 10, 0"
ConfigName="IdCard"
HeightRequest="59"
WidthRequest="335"
CardInfo="{Binding Path=/}"
CardTitle="{Binding StateTerritoryCardTitle}"/>
</Grid>
</Frame>
</StackLayout>
</DataTemplate>
</BindableLayout.ItemTemplate>
</StackLayout>
关于 CardInfo 属性 我也尝试了以下但没有成功 {Binding .} 和 {Binding}
控件代码:
public static readonly BindableProperty CardInfoProperty = BindableProperty.Create(nameof(CardInfo), typeof(IdCard), typeof(ThreeLineCardView), null);
private IdCard _idCard;
public IdCard CardInfo
{
get => (IdCard)GetValue(CardInfoProperty);
set
{
SetValue(CardInfoProperty, value);
_idCard = (IdCard) value;
}
}
并且页面绑定的集合在ViewModel中定义:
public ObservableCollection<IdCard> IdCardCollection { get; private set; }
我知道元素存在是因为我在控件中设置的第二个属性 CardTitle 确实有效。
更新 2 尝试使用对象作为属性类型,但这也不起作用(我在属性设置器中的 SetValue 方法调用上设置了一个断点)。见下文:
public static readonly BindableProperty CardInfoObjectProperty = BindableProperty.Create(nameof(CardInfoObject), typeof(object), typeof(ThreeLineCardView), null);
public object CardInfoObject
{
get => GetValue(CardInfoObjectProperty);
set
{
SetValue(CardInfoObjectProperty, value);
_idCard = (IdCard)value;
SetIdCardValues(_idCard);
}
}
<cardViews:ThreeLineCardView Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2"
Margin="0, 0, 10, 0"
ConfigName="IdCard"
HeightRequest="59"
WidthRequest="335"
CardInfoObject="{Binding .}"
CardTitle="{Binding StateTerritoryCardTitle}"/>
【问题讨论】:
-
如果您已经解决了这个问题,请采纳答案,它将帮助其他有类似问题的人。
标签: xaml xamarin.forms data-binding