C# - Xamarin Forms: Create Regex Instance in XAML

By , 3/10/2016
(0 ratings)
.NETs Regex class has not an public constructor that's why it cannot be instantiated in XAML.

This class gives the basics for solve this Problem. But it can be extended with the Regex properties too.

You can use it in a way like this:

<ns:MyControl AllowedUrlRegex="{controls:Regex Regex=(?i:^http://code-13.net/)}" />


Required Namespaces
System
System.Text.RegularExpressions
Xamarin.Forms.Xaml
/// <summary>
/// Provides a markup extension for initiating a <see cref="System.Text.RegularExpressions.Regex"/> instance.
/// </summary>
public class RegexExtension : IMarkupExtension<Regex>
{
    /// <summary>
    /// Creates a new instance of <see cref="RegexExtension"/>.
    /// </summary>
    public RegexExtension() { }

    /// <summary>
    /// Creates a new instance of <see cref="RegexExtension"/> with the given regex string.
    /// </summary>
    /// <param name="regex">The regex string to use.</param>
    public RegexExtension(string regex) : this()
    {
        this.Regex = regex;
    }

    /// <summary>
    /// Gets or sets the regex string.
    /// </summary>
    public string Regex { get; set; }

    /// <summary>
    /// Gets the regex as a <see cref="System.Text.RegularExpressions.Regex"/> instance.
    /// </summary>
    /// <param name="serviceProvider">Will be ignored.</param>
    /// <returns>A <see cref="System.Text.RegularExpressions.Regex"/> instance, creates from the <see cref="Regex"/> property.</returns>
    public Regex ProvideValue(IServiceProvider serviceProvider)
    {
        return new Regex(this.Regex);
    }

    object IMarkupExtension.ProvideValue(IServiceProvider serviceProvider)
    {
        return this.ProvideValue(serviceProvider);
    }
}

Comments

 

Log in, to comment!