Xamarin 获取ViewCell';构造函数中的s模型
对于这个用例,有一些问题没有真正的答案: 如何在其构造函数中检索当前的Xamarin 获取ViewCell';构造函数中的s模型,xamarin,xamarin.forms,Xamarin,Xamarin.forms,对于这个用例,有一些问题没有真正的答案: 如何在其构造函数中检索当前的ViewCell模型 例如,我希望访问模型中指定的单元格背景 我尝试过许多解决方案,比如将字符串属性绑定到单元格内的假标签对象,但在构造函数和OnAppearing方法中,它们都是null 例如,假设我有一个自定义单元格,需要显示标题、描述和可选图标。如果图标资源字符串为空,它将显示默认值: public class ListItem { public string title { get; set; } pu
ViewCell
模型
例如,我希望访问模型中指定的单元格背景
我尝试过许多解决方案,比如将字符串属性绑定到单元格内的假标签
对象,但在构造函数和OnAppearing
方法中,它们都是null
例如,假设我有一个自定义单元格,需要显示标题、描述和可选图标。如果图标资源字符串为空,它将显示默认值:
public class ListItem
{
public string title { get; set; }
public string description { get; set; }
public string icon { get; set; }
}
public class CustomCell : ViewCell
{
public CustomCell()
{
StackLayout cell = new StackLayout();
StackLayout text = new StackLayout()
{
Orientation = StackOrientation.Vertical
};
Label titleLabel = new Label();
Label descriptionLabel = new Label();
titleLabel.SetBinding(Label.TextProperty, "title");
descriptionLabel.SetBinding(Label.TextProperty, "description");
Image image = new Image();
// Custom icon
if (titleLabel.Text.Length != 0)
{
image.Source = ImageSource.FromResource(???);
}
else
{
image.Source = ImageSource.FromResource("myproject.icons.default.png");
}
text.Children.Add(titleLabel);
text.Children.Add(descriptionLabel);
cell.Children.Add(text);
cell.Children.Add(image);
View = cell;
}
}
有办法吗?您可以编写一个自定义视图单元格,它在构造函数中采用参数或模型,如下所示
public class CustomViewCell : ViewCell
{
public Bar bar;
pulic CustomViewCell(Foo foo)
{
bar = foo;
}
public GetCurrentModel()
{
return bar;
}
}
我不太明白,你能给我看一下你想要的代码吗?@JuniorJiang MSFT我已经用我想写的代码编辑了这个问题。
var model=CustomCell.BindingContext as ListItem
这是你想要的吗?@JuniorJiang MSFT是的,但是如果我使用var model=BindingContext as ListItem
,然后我得到null
。注意,我不得不修改您的代码,因为编译器抱怨静态成员。