【问题标题】:How to set min width or bigger in XAML of Xamarin.Forms如何在 Xamarin.Forms 的 XAML 中设置最小宽度或更大
【发布时间】:2021-01-21 11:00:56
【问题描述】:

我想知道如何将元素的宽度设置为最小 X 或更大。

例如,考虑下面的 XAML(为简单起见,仅包含屏幕截图中带有蓝色背景的文本的标记):

<Grid RowSpacing="0"
  ColumnSpacing="0">
<Grid.ColumnDefinitions>
    <ColumnDefinition Width="*" />
    <ColumnDefinition Width="Auto" />
    <ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>

<Label
    Grid.Column="1"
    Grid.Row="0"
    Margin="10,0,10,0"
    Text="Lorem ipsum"
    BackgroundColor="Aqua"
    FontSize="24"
    HorizontalOptions="Start"
    TextColor="{Binding TextColor}"
    WidthRequest="{OnIdiom Default=400, Phone=300}"/>
</Grid>

我希望蓝色背景的文本元素占据它所拥有的空间,但如果文本更大,我希望扩大宽度。

但现在对于较大的文本,它看起来像这样:

然而,我想让它看起来像这样(同时在第一个屏幕截图中仍然采用最小宽度):

【问题讨论】:

  • MinimumWidthRequest 实际上是非常糟糕的属性,并没有真正做到我想要的。根据一位 Xamarin 团队成员的说法:大多数人将其解释为“控件可以达到的最小尺寸,并且永远不会更小”,其中属性的实际意图是“当所需尺寸无法压缩时,控件可以压缩到的最小尺寸见面”。来源:forums.xamarin.com/discussion/84885/…
  • 使用行定义来限制您已经在使用网格
  • 有新的更新吗?

标签: .net xaml xamarin.forms


【解决方案1】:

也许您可以考虑使用CustomRenderer 来实现:

例如:

对于安卓:

创建一个MiniWidthLabel

public class MiniWidthLabel :Label
{
    public static readonly BindableProperty MinWidthProperty =BindableProperty.Create("MinWidth", typeof(int), typeof(MiniWidthLabel), null);
    public int MinWidth
    {
        get { return (int)GetValue(MinWidthProperty); }
        set { SetValue(MinWidthProperty, value); }
    }
}

在您的 Android 项目中创建一个 MinWidthLableRenderer

[assembly: ExportRenderer(typeof(MiniWidthLabel), typeof(MinWidthLableRenderer))]
namespace your namepace
{
 class MinWidthLableRenderer:LabelRenderer
  {

    public MinWidthLableRenderer(Context context) : base(context)
    {
    }
    protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
    {
        base.OnElementChanged(e);
        Control.SetMinWidth(((MiniWidthLabel)Element).MinWidth);

    }
  }
}

然后在你的 page.xaml 中使用:

<local:MiniWidthLabel Margin="10,0,10,0" Text="" BackgroundColor="Aqua"  MinWidth="200" FontSize="24" HorizontalOptions="Start"></local:MiniWidthLabel>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-06
    • 1970-01-01
    相关资源
    最近更新 更多