我在 Xamarin.Forms 中工作,尝试创建一个包含 ListView
的弹出窗口.
我正在尝试使用这种结构:
var PopUp = new StackLayout
{
BackgroundColor = Color.Black, // for Android and WP
Orientation = StackOrientation.Vertical,
Children =
{
PLZOrt_Label, // my Label on top
SearchBarPLZOrt, // my SearchBar to the ListView
LVPLZOrt, // The Listview (all Cities/Zip-Codes in the Datasource -> List)
}
};
取自this guide第 13 页。
但是,当我添加 ListView 时(详见 here),
new Func<object> (delegate {
ListView listView = new ListView {
// Source of data items.
ItemsSource = devices,
ItemTemplate = new DataTemplate(() =>
{
// Create views with bindings for displaying each property.
Label nameLabel = new Label();
nameLabel.SetBinding(
Label.TextProperty, "{Binding Name, Converter={StaticResource strConverter}}"
);
Label IDLabel = new Label();
IDLabel.SetBinding(
Label.TextProperty, "{Binding Path=ID, Converter={StaticResource guidConverter}}"
);
return new ViewCell
{
View = new StackLayout
{
})
});
“ItemTemplate”行抛出“无法将 Lambda 表达式转换为类型‘System.Type’,因为它不是委托(delegate)类型”
在像这样的其他一些问题中,解决方案似乎是添加一个 new action(() => {})
结构,但由于这是 Xamarin 批准的方法,我不确定为什么需要实现它?
谢谢!
编辑: 添加顶部的 func 行后,我现在在该行出现错误,Error CS1643: Not all code paths return a value in anonymous method of type 'System.Func<object>'
最佳答案
从 DataTemplate
的构造函数中可以看出here ,您需要传递 Func<object>
或 Type
.
你需要在你的 statement block 中返回一些东西为了将其转换为 Func<object>
.由于您没有 return 语句,因此不会转换 lambda,编译器认为您正在尝试使用 DataTemplate(Type)
参数错误的构造函数。我不知道为什么 C# 编译器选择这个构造函数 - 我猜这是它找到的第一个。
ListView
文档页面上的示例您链接的页面有效,因为它返回一个新的 ViewCell
:
// ...
ItemTemplate = new DataTemplate(() =>
{
// Create views with bindings for displaying each property.
Label nameLabel = new Label();
nameLabel.SetBinding(Label.TextProperty, "Name");
Label birthdayLabel = new Label();
birthdayLabel.SetBinding(Label.TextProperty,
new Binding("Birthday", BindingMode.OneWay,
null, null, "Born {0:d}"));
BoxView boxView = new BoxView();
boxView.SetBinding(BoxView.ColorProperty, "FavoriteColor");
// Return an assembled ViewCell. <<--------------------------------------
return new ViewCell
{
View = new StackLayout
{
Padding = new Thickness(0, 5),
Orientation = StackOrientation.Horizontal,
Children =
{
boxView,
new StackLayout
{
VerticalOptions = LayoutOptions.Center,
Spacing = 0,
Children =
{
nameLabel,
birthdayLabel
}
}
}
}
};
})
// ...
编辑:这就是我将 lambda 放在 new Func<object>(...):
中的意思
ListView listView = new ListView
{
// Source of data items.
ItemsSource = devices,
ItemTemplate = new DataTemplate(new Func<object>(() =>
{
// Create views with bindings for displaying each property.
Label nameLabel = new Label();
nameLabel.SetBinding(
Label.TextProperty, "{Binding Name, Converter={StaticResource strConverter}}"
);
Label IDLabel = new Label();
IDLabel.SetBinding(
Label.TextProperty, "{Binding Path=ID, Converter={StaticResource guidConverter}}"
);
return new ViewCell
{
View = new StackLayout
};
}));
}
关于c# - 无法将 Lambda 表达式转换为类型 'System.Type',因为它不是委托(delegate)类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32285167/