我正在研究微软页面上的文档,因为我愿意学习xamarin.forms。每当引入新的主题时,我都会尝试编写一个小应用程序来测试我刚刚学到的内容。在尝试xaml标记扩展时,我发现microsoft文档中显示的其中一个示例对我不起作用,即使我从网站上复制它并将其粘贴到我的vs项目中也是如此。
C#代码是这样的
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace XamarinLab
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
}
public class HslColorExtension : IMarkupExtension<Color>
{
public double H { set; get; }
public double S { set; get; }
public double L { set; get; }
public double A { set; get; } = 1.0;
public Color ProvideValue(IServiceProvider serviceProvider)
{
return Color.FromHsla(H, S, L, A);
}
object IMarkupExtension.ProvideValue(IServiceProvider serviceProvider)
{
return (this as IMarkupExtension<Color>).ProvideValue(serviceProvider);
}
}
}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:XamarinLab"
x:Class="XamarinLab.MainPage">
<ContentPage.Resources>
<ResourceDictionary>
<Style TargetType="BoxView">
<Setter Property="WidthRequest" Value="80" />
<Setter Property="HeightRequest" Value="80" />
<Setter Property="HorizontalOptions" Value="Center" />
<Setter Property="VerticalOptions" Value="CenterAndExpand" />
</Style>
</ResourceDictionary>
</ContentPage.Resources>
<StackLayout>
<BoxView>
<BoxView.Color>
<local:HslColorExtension H="0" S="1" L="0.5" A="1" />
</BoxView.Color>
</BoxView>
<BoxView>
<BoxView.Color>
<local:HslColor H="0.33" S="1" L="0.5" />
</BoxView.Color>
</BoxView>
<BoxView Color="{local:HslColorExtension H=0.67, S=1, L=0.5}" />
<BoxView Color="{local:HslColor H=0, S=0, L=0.5}" />
<BoxView Color="{local:HslColor A=0.5}" />
</StackLayout>
</ContentPage>当我尝试运行应用程序时,弹出以下异常
markup extension not found for local:HslColorExtension我复制的示例位于:https://docs.microsoft.com/it-it/xamarin/xamarin-forms/xaml/markup-extensions/creating
这是第一个例子,提前感谢大家的帮助。
发布于 2019-01-28 19:13:09
您需要在项目中创建一个新的file类,名为HslColorExtension,而不是在MainPage文件中创建一个类,在这个文件中,它将无法识别名称空间或创建的类。
只需将该部分移动到一个新文件中,您就应该都设置好了。
您可以查看Offical Sample,以查看其结构、文件和如何设置。
https://stackoverflow.com/questions/54400512
复制相似问题