【发布时间】:2019-10-25 23:40:18
【问题描述】:
我已阅读有关在 Xamarin Forms 中的 XAML/Shared Library 项目中创建共享图像的示例和文档,但是,这些示例并未向我展示如何绑定到 list共享图片。
我应该如何将带有 DataTemplate 的 ListView 绑定到我存储在共享项目中的一大堆图像?
【问题讨论】:
标签: c# xamarin mobile xamarin.forms
我已阅读有关在 Xamarin Forms 中的 XAML/Shared Library 项目中创建共享图像的示例和文档,但是,这些示例并未向我展示如何绑定到 list共享图片。
我应该如何将带有 DataTemplate 的 ListView 绑定到我存储在共享项目中的一大堆图像?
【问题讨论】:
标签: c# xamarin mobile xamarin.forms
这有点棘手 - 嵌入式资源的命名“约定”有点奇怪,如果出现任何问题,输出通常类似于“找不到图像”或“您的绑定错误” ”。
我可以通过查看 WorkingWithImages 代码 here 并尝试在 C# 和 XAML 中创建 ListView 来完成这项工作。
首先,绑定模型(ListView 绑定到的 POCO 类)如下所示:
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;
这是一个有效的 XAML 示例,来自 PeopleSearchPage:
<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;
});
【讨论】: