I would like to throw an exception during compilation time if the given parameter in the IMarkupExtension is not compatible with the type expected by me. Can I achieve this effect?
Below I put my experiments, but I do not know where and how to check what I wrote in "TODO"
Code (I marked todo)
using System;
using Xamarin.Forms.Xaml;
namespace MySample
{
public class SampleClass : IMarkupExtension
{
public IParameter Parameter { get; set; }
public object ProvideValue(IServiceProvider serviceProvider)
{
return Parameter.GetData();//TODO: throw Exception("Parameter must be of type SampleData1")
}
}
public interface IParameter
{
string GetData();
}
public class SampleData1 : IParameter
{
public string GetData()
{
return "Data1";
}
}
public class SampleData2 : IParameter
{
public string GetData()
{
return "Data2";
}
}
}
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:mysample="clr-namespace:MySample"
x:Class="MySample.SamplePage">
<ContentPage.Resources>
<mysample:SampleData2 x:Key="SampleData2" />
</ContentPage.Resources>
<ContentPage.Content>
<StackLayout>
<Label>
<Label.Text>
<mysample:SampleClass Parameter="{StaticResource SampleData2}" />
</Label.Text>
</Label>
</StackLayout>
</ContentPage.Content>
</ContentPage>
Please note that the parameter is of the SampleData2 type, but I want to throw an exception if it is not of the SampleData1 type.
Resource
<mysample:SampleData2 x:Key="SampleData2" />
Resource usage
Parameter="{StaticResource SampleData2}"
Check (not necessarily in this place, but definitely during compilation)
public object ProvideValue(IServiceProvider serviceProvider)
{
return Parameter.GetData();//TODO: throw Exception("Parameter must be of type SampleData1")
}