Mic*_*eni 2 listview xamarin xamarin.forms
我刚开始使用 Xamarin.Forms,我有一个关于 ListView 的问题,但在网上找不到答案。在下面的代码中,我需要在 ItemTemplate 中获取元素的索引或访问单元格中显示的 ItemSource 的方法,因为我需要构建显示图像的路径。如果我可以同时拥有索引和元素,那就更好了。任何不使用 CustomRenderer 的方法?
ListView listView = new ListView
{
HasUnevenRows = true,
// Source of data items.
ItemsSource = DataManager.GetPeople(),
ItemTemplate = new DataTemplate(() =>
{
// Create views with bindings for displaying each property.
Label nameLabel = new Label();
nameLabel.SetBinding(Label.TextProperty, "Name");
nameLabel.TextColor = Color.White;
var relativeLayout = new RelativeLayout {};
var webImage = new Image { Aspect = Aspect.AspectFill };
image.HeightRequest = 200;
image.Source = ImageSource.FromFile(Path.Combine(path, "/people/263/1.jpg"));
relativeLayout.Children.Add(image,Constraint.Constant(0),Constraint.Constant(0));
relativeLayout.Children.Add(nameLabel,
Constraint.RelativeToParent((parent) => {
return parent.Width / 2 - nameLabel.Width / 2;
}),
Constraint.RelativeToParent((parent) =>
{
return parent.Height - 20;
}));
// Return an assembled ViewCell.
var viewCell = new ViewCell
{
View = relativeLayout
};
viewCell.Height = 200;
relativeLayout.HeightRequest = 200;
return viewCell;
})
};
Run Code Online (Sandbox Code Playgroud)
小智 5
这可以使用转换器来完成。您可以从下面的示例中看到如何通过将 ListView 作为引用传递来访问元素 BindingContext(value) 和索引。您可以使用转换器来构建图像路径并将其绑定到图像源。
public class ImageSourceIndexConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null || parameter == null) return Color.White;
var index = ((ListView) parameter).ItemsSource.Cast<object>().ToList().IndexOf(value);
return ImageSource.FromFile(Path.Combine(path, "/people/"+index+"/1.jpg"));
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Run Code Online (Sandbox Code Playgroud)
然后命名您的 ListView 并使用 x:Reference 将其作为参数传递
<ListView x:Name="PeopleListView" ItemsSource="{Binding People}" SelectedItem="{Binding SelectedPerson, Mode=TwoWay}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid>
<Image Source={Binding .,Converter={StaticResource StripedBackgroundIndexConverter}, ConverterParameter={x:Reference PeopleListView}}" />
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6681 次 |
| 最近记录: |