如何制作固定元素宽度(frame 或 stacklayout)

How to make a fixed element width (frame or stacklayout)

我使用 absoluteLayOut 在 Android Xamarin.Forms 上制作了一个框架!我的目标是从设备宽度设置一点space!但是当我在两个设备上尝试时,框架的高度和宽度完全减少了..

https://i.stack.imgur.com/8kjzD.jpg

<AbsoluteLayout>
    <Frame AbsoluteLayout.LayoutBounds="0.5,0.5,310,340" AbsoluteLayout.LayoutFlags="PositionProportional" CornerRadius="15" Padding="0">

        <AbsoluteLayout BackgroundColor="Black">
            <Label Text="mos.Softs" FontAttributes="Bold" FontSize="16" TextColor="Wheat"
                   AbsoluteLayout.LayoutBounds="0.5,0.011" AbsoluteLayout.LayoutFlags="PositionProportional"></Label>
            
            <Label x:Name="lblWidth" FontAttributes="Bold" FontSize="16" TextColor="Wheat"
                   AbsoluteLayout.LayoutBounds="0.5,0.5" AbsoluteLayout.LayoutFlags="PositionProportional"></Label>

            <Button Padding="0" CornerRadius="5" Text="Click me" TextTransform="None"
                    AbsoluteLayout.LayoutBounds="0.5,0.98, 100,40" AbsoluteLayout.LayoutFlags="PositionProportional"></Button>
        </AbsoluteLayout>
    </Frame>
</AbsoluteLayout>

您可以使用转换器来适应尺寸而不是 AbsoluteLayout

首先将名称设置为您的框架。

    <Frame
 …………
x:Name="frame"/>

创建 MyConverter: MyConverter.cs

public class MyConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return (double)value / 3.0;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

设置静态资源:

 <ContentPage.Resources>
    <ResourceDictionary>
        <local:MyConverter x:Key="MyConverter" />
    </ResourceDictionary>
</ContentPage.Resources>

为帧值绑定:

 <Frame x:Name="frame" >
        <StackLayout BackgroundColor="Gray" VerticalOptions="CenterAndExpand" WidthRequest="{Binding Source={x:Reference frame},Path=Width,Converter={StaticResource MyConverter}}"
                    HeightRequest="{Binding Source={x:Reference frame},Path=Height,Converter={StaticResource MyConverter}}" >
            
            <Label Text="mos.Softs" FontAttributes="Bold" FontSize="16" TextColor="Wheat"
                    HorizontalOptions="CenterAndExpand" VerticalOptions="StartAndExpand" ></Label>

            <Label  Text="Device Height" x:Name="lblWidth" FontAttributes="Bold" FontSize="16" TextColor="Wheat"
                    HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand"></Label>

            <Button Padding="0" CornerRadius="5" Text="Click me" TextTransform="None"
                    HorizontalOptions="CenterAndExpand" VerticalOptions="EndAndExpand" ></Button>

        </StackLayout>
    </Frame>