Xamarin窗体:将*共享资源*图像绑定到ListView



我已经阅读了在Xamarin Forms的XAML/共享库项目中创建共享图像的示例和文档,但是这些示例并没有向我展示如何绑定到共享图像的列表

我应该如何将带有DataTemplate的ListView绑定到我存储在共享项目中的一大堆图像?

这有点棘手-嵌入式资源的命名"约定"有点奇怪,如果出现任何问题,输出通常是"找不到图像"或"绑定错误"。

我能够通过在这里浏览WorkingWithImages代码和在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;
});

相关内容

  • 没有找到相关文章

最新更新