首页 文章

xamarin PCL形成共享的自定义控件

提问于
浏览
1

我读了很多关于 controls customizations 的帖子 . 我的问题非常简单:每个教程帖都谈到在PCL共享项目中创建自定义渲染器,并在具有特定渲染器的每个平台中实现它 .

示例:xamarin指南和xamarin博客上的thisthis帖子 .

有没有办法在PCL共享项目中只实现一次并在任何地方使用它?

我的目标是创建一个可能是新的自定义控件,例如包含一些矩形和一些标签的控件 . 或任何你能想象到的东西 . 我无法实现的唯一功能是仅在共享项目中实现 .

谢谢大家,任何回复将不胜感激

2 回答

  • 2

    自定义渲染器是特定于平台的 . 它们的目的是将Xamarin.Forms元素转换为本机控件 .

    您的用例听起来像一个复合控件 . 你可以做的是将所有可用的控件包装成可重用的组件 .

    MyControl.xaml

    <?xml version="1.0" encoding="utf-8" ?>
    <StackLayout xmlns="http://xamarin.com/schemas/2014/forms"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 x:Class="App3.MyControl">
        <Label Text="Hello World" VerticalOptions="Center" HorizontalOptions="Center" />
        <BoxView BackgroundColor="Fuchsia"></BoxView>
        <!-- add whatever you want -->
    </StackLayout>
    

    MyControl.xaml.cs

    public partial class MyControl : StackLayout
    {
        public MyControl()
        {
            InitializeComponent();
        }
    }
    

    Page1.xaml

    你可以在你的页面中使用它 .

    <?xml version="1.0" encoding="utf-8" ?>
    <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 xmlns:local="clr-namespace:App3;assembly=App3"
                 x:Class="App3.Page1">
        <local:MyControl></local:MyControl>
    </ContentPage>
    
  • 1

    您需要针对不同平台的自定义渲染器,以便您可以访问平台提供的本机窗口小部件 .

    但是,如果您想自己绘制所有自定义控件,可以使用skiasharp跨平台绘图库来实现结果 . 有关详细信息,请参阅此博客文章:Cross-Platform 2D Graphics with SkiaSharp

相关问题