问题描述
添加到我的代码中
new InfoLabel()`{ Text = "abc" };
请注意,这只是一个非常简单的示例,我还有其他不只依赖于一件事的模板对象,例如具有 2-3 个标签的对象。
有没有一种方法可以应用 Xamarin C# fluent 创建模板化对象?
这是我拥有的简单示例对象:
namespace Test
{
public class InfoLabel : Label
{
public InfoLabel()
{
SetDynamicResource(FontFamilyProperty,Const.Fonts.DefaultRegular);
SetDynamicResource(FontSizeProperty,Const.Fonts.InfoTextFontSize);
SetDynamicResource(TextColorProperty,Const.Colors.InfoLabelColor);
LineBreakMode = LineBreakMode.WordWrap;
VerticalOptions = Layoutoptions.Start;
HorizontalTextAlignment = TextAlignment.Start;
}
}
}
我想知道如何使用最新的 C# fluent 标准设置相同的东西?
这是我认为可能完成的方式。我使用了 Build()
方法,但如果有人比我更熟练,能告诉我是否正确执行,我将不胜感激,因为这与我习惯的方法相比有很大变化:
namespace Test
{
public class InfoLabel
{
public InfoLabel()
{
Build();
}
void Build() =>
new Label
{
LineBreakMode = LineBreakMode.WordWrap,}
.TextLeft()
.DynamicResources((Label.FontFamilyProperty,Const.Fonts.DefaultRegular),(Label.FontSizeProperty,Const.Fonts.InfoTextFontSize),(Label.TextColorProperty,Const.Colors.InfoLabelColor));
这是我的另一个想法:
namespace Test
{
public class InfoLabel : Label
{
public InfoLabel()
{
LineBreakMode = LineBreakMode.WordWrap;
Build();
}
void Build() =>
this.TextLeft()
.DynamicResources((Label.FontFamilyProperty,Const.Colors.InfoLabelColor));
请注意,我对资源使用了扩展方法。
解决方法
你可以像下面这样创建标签的实例
public class InfoLabel : Label
{
static InfoLabel CreateDefaultLabel()
{
return new InfoLabel
{
LineBreakMode = LineBreakMode.WordWrap,}
.TextLeft()
.DynamicResources((Label.FontFamilyProperty,Const.Fonts.DefaultRegular),(Label.FontSizeProperty,Const.Fonts.InfoTextFontSize),(Label.TextColorProperty,Const.Colors.InfoLabelColor));
}
}
var label = InfoLabel.CreateDefaultLabel();
有关标记用法的更多详细信息,您可以查看此blog。