在 XAML 预览器中呈现自定义控件Render Custom Controls in the XAML Previewer

自定义控件有时在 XAML 预览器中不按预期方式工作。使用本文中的指南来了解预览自定义控件的限制。Custom controls sometimes don't work as expected in the XAML Previewer. Use the guidance in this article to understand the limitations of previewing your custom controls.

基本预览模式Basic Preview mode

即使您未生成项目,XAML 预览器也会呈现您的页面。Even if you haven't built your project, the XAML Previewer will render your pages. 在生成之前,依赖于代码隐藏的任何控件都将显示其基本 Xamarin。窗体类型。Until you build, any control that relies on code-behind will show its base Xamarin.Forms type. 生成项目时,XAML 预览器会尝试在启用设计时呈现的情况下显示自定义控件。When your project is built, the XAML Previewer will try to show custom controls with design time rendering enabled. 如果呈现失败,它将显示基本 Xamarin. 窗体类型。If the render fails, it will show the base Xamarin.Forms type.

启用自定义控件的设计时呈现Enable design time rendering for custom controls

如果创建自己的自定义控件或使用第三方库中的控件,则预览程序可能会错误地显示这些控件。If you make your own custom controls, or use controls from a third-party library, the Previewer might display them incorrectly. 无论是从库中写入控件还是从库中导入,自定义控件都必须选择将时间呈现设计为显示在预览器中。Custom controls must opt in to design time rendering to appear in the previewer, whether you wrote the control or imported it from a library. 如果已创建控件,请将添加[DesignTimeVisible(true)]到控件的类,以便在预览器中显示它:With controls you've created, add the [DesignTimeVisible(true)] to your control's class to show it in the Previewer:

namespace MyProject
{
  [DesignTimeVisible(true)]
  public class MyControl : BaseControl
  {
    // Your control's code here
  }

}

使用James Montemagno 的 ImageCirclePlugin's 基类作为示例。Use James Montemagno's ImageCirclePlugin's base class as an example.

SkiaSharp 控件SkiaSharp controls

目前,仅当你在 iOS 上预览时,才支持 SkiaSharp 控件。Currently, SkiaSharp controls are only supported when you're previewing on iOS. 它们不会在 Android 预览版中呈现。They won't render on the Android preview.

疑难解答Troubleshooting

检查 Xamarin. Forms 版本Check your Xamarin.Forms version

请确保至少安装了 Xamarin. Forms 3.6。Make sure you have at least Xamarin.Forms 3.6 installed. 可以在 NuGet 上更新 Xamarin. Forms 版本。You can update your Xamarin.Forms version on NuGet.

即使有[DesignTimeVisible(true)],自定义控件也不会正确呈现。Even with [DesignTimeVisible(true)], my custom control isn't rendering properly.

很大程度上依赖于代码隐藏或后端数据的自定义控件并不总是在 XAML 预览器中工作。Custom controls that rely heavily on code-behind or backend data don't always work in the XAML Previewer. 你可以尝试:You can try:

XAML 预览器显示错误 "自定义控件不能正确呈现"The XAML Previewer shows the error "Custom Controls aren't rendering properly"

尝试清除并重新生成项目,或关闭并重新打开 XAML 文件。Try cleaning and rebuilding your project, or closing and reopening the XAML file.