0
votes

Good Day,

I am trying to implement a WPF Hyperlink that will open the default mailclient with the email address. Thats it.

Now I have browsed many many examples but each example almost uses an event or parameter being passed throught to the command. Is there any other way I can achieve this. The email address is bounded? Keep the MVVM principle in mind. This is what I've got sofar:

<TextBlock  Grid.Column="3" HorizontalAlignment="Left" VerticalAlignment="Center">
    <Hyperlink NavigateUri="mailto:[email protected]">
        <Run Text="{Binding Email}" />
     </Hyperlink>
</TextBlock>
1

1 Answers

2
votes

You can try Converter as below,

<TextBlock Grid.Column="3"
               HorizontalAlignment="Left"
               VerticalAlignment="Center">
        <TextBlock.Resources>
            <local:StringToMailToConverer x:Key="StringToMailToConverer" />
        </TextBlock.Resources>
        <Hyperlink NavigateUri="{Binding Email, Converter={StaticResource StringToMailToConverer}}">
            <Run Text="{Binding Email}" />
        </Hyperlink>
    </TextBlock>

converter,

 public class StringToMailToConverer : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
       if(value != null)
        {
            if (!string.IsNullOrEmpty(value.ToString()))
            {
                return "mailto:" + value.ToString();
            }
        }
        return string.Empty;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Update In that case, you can use simple behaviour,

 <TextBlock xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
               Grid.Column="3"
               HorizontalAlignment="Left"
               VerticalAlignment="Center">
        <Hyperlink NavigateUri="{Binding Email}">
            <i:Interaction.Behaviors>
                <local:MailToBehaviour />
            </i:Interaction.Behaviors>
            <Run Text="{Binding Email}" />
        </Hyperlink>
    </TextBlock>

public class MailToBehaviour : Behavior<Hyperlink>
{
    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.RequestNavigate += (_, __) =>
        {
            Process.Start("mailto:" + __.Uri);
            __.Handled = true;
        };
    }
}

you need to refer System.Windows.Interactivity assembly