C#标记开发自定义DateTimePicker如何实现Label居中对齐及边框适配
调整方案
- 解决Frame宽度超出内容的问题:给Frame设置
HorizontalOptions = LayoutOptions.Center,默认Frame是横向撑满父容器的,改成Center后会自动适配内容的实际宽度。 - 实现标签在输入框上方居中:把每一组「标签+输入框」封装到一个垂直方向的
StackLayout中,设置标签的水平对齐属性为居中,输入框的文本也设置居中对齐即可。
修改后的构造函数代码如下:
public DateTimePicker2() { BindingContext = this; // 可根据需要调整输入框宽度,适配标签显示 const int entryWidth = 45; _dayEntry.WidthRequest = entryWidth; _monthEntry.WidthRequest = entryWidth; _yearEntry.WidthRequest = entryWidth; _hourEntry.WidthRequest = entryWidth; _minsEntry.WidthRequest = entryWidth; // 输入框文本居中 _dayEntry.HorizontalTextAlignment = TextAlignment.Center; _monthEntry.HorizontalTextAlignment = TextAlignment.Center; _yearEntry.HorizontalTextAlignment = TextAlignment.Center; _hourEntry.HorizontalTextAlignment = TextAlignment.Center; _minsEntry.HorizontalTextAlignment = TextAlignment.Center; Content = new Frame() { BorderColor = Color.Black, CornerRadius = 30, Padding = new Thickness(15, 10, 15, 10), Margin = new Thickness(20), // 关键:让Frame宽度适配内容,不撑满父容器 HorizontalOptions = LayoutOptions.Center, Content = new StackLayout { Orientation = StackOrientation.Horizontal, Spacing = 12, // 调整每组之间的间距 Children = { // 日 分组 new StackLayout { Orientation = StackOrientation.Vertical, Spacing = 4, Children = { _dayLabel, _dayEntry } }, // 月 分组 new StackLayout { Orientation = StackOrientation.Vertical, Spacing = 4, Children = { _monthLabel, _monthEntry } }, // 年 分组 new StackLayout { Orientation = StackOrientation.Vertical, Spacing = 4, Children = { _yearLabel, _yearEntry } }, // 时 分组 new StackLayout { Orientation = StackOrientation.Vertical, Spacing = 4, Children = { _hourLabel, _hourEntry } }, // 分 分组 new StackLayout { Orientation = StackOrientation.Vertical, Spacing = 4, Children = { _minLabel, _minsEntry } } } } }; // 所有标签水平居中 _dayLabel.HorizontalOptions = LayoutOptions.Center; _monthLabel.HorizontalOptions = LayoutOptions.Center; _yearLabel.HorizontalOptions = LayoutOptions.Center; _hourLabel.HorizontalOptions = LayoutOptions.Center; _minLabel.HorizontalOptions = LayoutOptions.Center; }
如果后续要加AM/PM选择器、12/24小时切换选择器,也可以用同样的方式新增垂直StackLayout组放到根横向StackLayout的Children里即可。
内容的提问来源于stack exchange,提问作者dotnetdevcsharp
相关产品推荐
相关产品推荐

