如何在Xamarin Forms的UWP平台为Frame设置1、2或3个圆角?
在Xamarin Forms UWP平台为Frame设置指定角的圆角
Xamarin Forms原生Frame控件在UWP平台默认只能统一设置四个角的圆角,要实现单个、两个或三个角的自定义圆角,需要通过自定义控件+UWP平台自定义Renderer来实现,具体步骤如下:
1. 在共享项目中创建自定义Frame控件
创建继承自Frame的自定义控件,添加用于指定各角圆角值的绑定属性:
using Xamarin.Forms; namespace YourAppName { public class CustomCornerFrame : Frame { public static readonly BindableProperty CornerRadiusProperty = BindableProperty.Create( nameof(CornerRadius), typeof(CornerRadius), typeof(CustomCornerFrame), new CornerRadius(0)); public CornerRadius CornerRadius { get => (CornerRadius)GetValue(CornerRadiusProperty); set => SetValue(CornerRadiusProperty, value); } } }
2. 在UWP项目中实现自定义Renderer
创建对应CustomCornerFrame的Renderer,将自定义的圆角值映射到UWP原生控件的CornerRadius属性:
using YourAppName; using YourAppName.UWP; using Xamarin.Forms; using Xamarin.Forms.Platform.UWP; [assembly: ExportRenderer(typeof(CustomCornerFrame), typeof(CustomCornerFrameRenderer))] namespace YourAppName.UWP { public class CustomCornerFrameRenderer : FrameRenderer { protected override void OnElementChanged(ElementChangedEventArgs<Frame> e) { base.OnElementChanged(e); UpdateCornerRadius(); } protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { base.OnElementPropertyChanged(sender, e); if (e.PropertyName == CustomCornerFrame.CornerRadiusProperty.PropertyName) { UpdateCornerRadius(); } } private void UpdateCornerRadius() { if (Element is CustomCornerFrame customFrame && Control != null) { Control.CornerRadius = new Windows.UI.Xaml.CornerRadius( customFrame.CornerRadius.TopLeft, customFrame.CornerRadius.TopRight, customFrame.CornerRadius.BottomRight, customFrame.CornerRadius.BottomLeft); } } } }
3. 在XAML中使用自定义圆角Frame
通过CornerRadius属性分别指定四个角的圆角值(顺序:左上、右上、右下、左下),不需要圆角的角设为0即可:
示例1:仅顶部两个角圆角
<local:CustomCornerFrame CornerRadius="10,10,0,0" BackgroundColor="#E1F5FE" Padding="12" WidthRequest="220" HeightRequest="100"> <Label Text="顶部两角圆角" HorizontalOptions="Center" VerticalOptions="Center"/> </local:CustomCornerFrame>
示例2:仅右下角圆角
<local:CustomCornerFrame CornerRadius="0,0,15,0" BackgroundColor="#DCEDC8" Padding="12" WidthRequest="220" HeightRequest="100"> <Label Text="仅右下角圆角" HorizontalOptions="Center" VerticalOptions="Center"/> </local:CustomCornerFrame>
效果示例

内容的提问来源于stack exchange,提问作者Việt Anh Nguyễn
相关产品推荐
相关产品推荐

