在我的 View 代码中,我创建了一个模型类型的对象。我将该对象添加到 ObservableCollection 中,并在 StackLayout 的 XAML 代码中绑定(bind)到该集合。我在 StackLayout 内放置了一个自定义控件(ContentView)。我希望能够使用 ObservableCollection 中的整个对象在控件上设置属性。然后,控件将从对象集的各个部分设置自己的内容。如果这有点令人困惑,让我演示一下我想要做什么。
更新 我修改了我的代码(XAML 和 C#),尝试根据 Jason 提供的信息(下面的注释)并使用我在 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 属性上我也尝试了以下操作,但没有成功 {绑定(bind).}和{绑定(bind)}
控件代码:
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;
}
}
页面绑定(bind)到的集合在 ViewModel 中定义:
public ObservableCollection<IdCard> IdCardCollection { get; private set; }
我知道该元素存在,因为我在控件中设置的第二个属性 CardTitle 确实有效。
更新2 尝试使用对象作为属性类型,但这也不起作用(我在属性 setter 中的 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}"/>
最佳答案
使用"{Binding .}"
关于xaml - 如何将 Observable Collection 的整个元素绑定(bind)到 Xamarin Forms 中的 ContentView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62562862/