我相信你应该能够通过简单地在CommentBlock
代码隐藏中添加一个构造函数来实现这一点,并且仍然继续使用基于 XAML 的工作CommentBlock
:
public CommentBlock(string text, double height)
{
InitializeComponent();
_commentLbl.Text = text;
_containerGrid.HeightRequest = height;
}
CommentBlock
并在XAML中添加对内部控件的命名引用:
<Grid x:Name="_containerGrid" ..>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Label x:Name="_commentLbl" ../>
</Grid>
编辑:08/23
但是,如果您特别寻找基于 C# 的实现,那么以下将是您的 XAML 的 C# 等效项(我为注释文本和网格高度添加了几个可绑定属性以允许基于 XAML 的使用)。
public class CommentBlockCell : ViewCell
{
public static readonly BindableProperty CommentTextProperty = BindableProperty.Create(
"CommentText", typeof(string), typeof(CommentBlockCell),
defaultValue: null);
public string CommentText
{
get { return (string)GetValue(CommentTextProperty); }
set { SetValue(CommentTextProperty, value); }
}
public static readonly BindableProperty GridHeightProperty = BindableProperty.Create(
"GridHeight", typeof(double), typeof(CommentBlockCell),
defaultValue: 30.0);
public double GridHeight
{
get { return (double)GetValue(GridHeightProperty); }
set { SetValue(GridHeightProperty, value); }
}
public CommentBlockCell()
{
BuildControl();
}
public CommentBlockCell(double gridHeight, string comment)
{
CommentText = comment;
GridHeight = gridHeight;
BuildControl();
}
private void BuildControl()
{
var grid = new Grid
{
VerticalOptions = LayoutOptions.CenterAndExpand,
Padding = new Thickness(20, 10),
BackgroundColor = Color.FromHex("#EAEAF1"),
RowDefinitions = new RowDefinitionCollection {
new RowDefinition { Height = GridLength.Auto }
},
ColumnDefinitions = new ColumnDefinitionCollection {
new ColumnDefinition { Width = GridLength.Auto }
}
};
var label = new Label
{
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.CenterAndExpand
};
//label.SetDynamicResource(VisualElement.StyleProperty, "ListItemDetailTextStyleStyle");
label.SetBinding(Label.TextProperty, new Binding(nameof(CommentText), source: this));
grid.SetBinding(VisualElement.HeightRequestProperty, new Binding(nameof(GridHeight), source: this));
grid.Children.Add(label);
View = grid;
}
}
用法可以是:
new CommentBlockCell(60, "ABC");
或在 XAML 中:
<local:CommentBlockCell CommentText="ABC" GridHeight="60" />