[英]Xamarin Forms: Binding *Shared Resource* Images to a ListView?
我已经阅读了有关在 Xamarin Forms 的 XAML/共享库项目中创建共享图像的示例和文档,但是,这些示例没有向我展示如何绑定到共享图像列表。
我应该如何 go 关于将 ListView 与 DataTemplate 绑定到我存储在共享项目中的一大堆图像?
这有点棘手 - 嵌入式资源的命名“约定”有点奇怪,如果出现任何问题,output 通常类似于“找不到图像”或“您的绑定错误”。
我可以通过查看 WorkingWithImages 代码和在C#和 XAML 中创建 ListView 的组合来完成这项工作。
首先,这是绑定 model(ListView 绑定到的 POCO class)的样子:
People = new List<PeopleSearchCell>();
People.Add(new PeopleSearchCell
{
Name = "My Name",
List = "Some string list",
EmbeddedPhoto = ImageSource.FromResource("YOUR_ASSEMBLY_NAME_HERE.Folder1.Folder2.ACTUAL_IMAGE_NAME.jpeg", typeof(PeopleSearchPage).GetTypeInfo().Assembly)
}) ;
BindingContext = this;
这是来自 PeopleSearchPage 的 XAML 示例:
<ListView ItemsSource="{Binding People}"
ItemSelected="OnListViewItemSelected"
ItemTapped="OnListViewItemTapped"
HasUnevenRows="True"
x:Name="PeopleList"
>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid Padding="10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Image Grid.RowSpan="2"
Grid.Column="0"
Source="{Binding EmbeddedPhoto}"
Aspect="AspectFill"
HeightRequest="80"
WidthRequest="80"
/>
<Label Grid.Row="0"
Grid.Column="1"
Text="{Binding Name}"
FontAttributes="Bold"
/>
<Label Grid.Row="1"
Grid.Column="1"
Text="{Binding List}"
VerticalOptions="End" />
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
或者,在 C# 中创建 ListView:
PeopleListView.ItemTemplate = new DataTemplate(() =>
{
ViewCell vc = new ViewCell();
Grid vcGrid = new Grid();
vcGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) });
vcGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
vcGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Auto) });
vcGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
var gridImg = new Image();
gridImg.SetBinding(Image.SourceProperty, "EmbeddedPhoto");
gridImg.HeightRequest = 80;
gridImg.WidthRequest = 80;
gridImg.Aspect = Aspect.AspectFill;
vcGrid.Children.Add(gridImg, 0, 0);
Grid.SetRowSpan(gridImg, 2);
var nameLabel = new Label();
nameLabel.SetBinding(Label.TextProperty, "Name");
nameLabel.FontAttributes = FontAttributes.Bold;
vcGrid.Children.Add(nameLabel, 1, 0);
var clientsLabel = new Label();
clientsLabel.SetBinding(Label.TextProperty, "List");
clientsLabel.VerticalOptions = new LayoutOptions(LayoutAlignment.End, false);
vcGrid.Children.Add(nameLabel, 1, 1);
vc.View = vcGrid;
return vc;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.