Question

Question: How to create hyperlinked Image with rounded corners in WPF/XAML?

So far, existing code for hyperlinked image (no rounded corners) is working (see below):

Hyperlinked Image (WPF XAML)

<TextBlock Name="txtbFooterRight" >
    <Hyperlink Name="lnkImg" TextDecorations="None" 
     NavigateUri="http://webinfocentral.com" 
     ToolTip="Navigate to web page">
        <Image Name="someName" Source="some url" />
    </Hyperlink>
 </TextBlock>

Hyperlinked image code behind (C#):

lnkImg.RequestNavigate += (s, e) => {Process.Start(e.Uri.ToString()); };

Image control with rounded corners (no hyperlinks) is implemented as:

Image with rounded corners (WPF/XAML):

<Border Name="brdRounded" BorderThickness="0" CornerRadius="10">
    <Border.Background >
        <ImageBrush>
            <ImageBrush.ImageSource>
                <BitmapImage UriSource="some Uri to .jpg" />
            </ImageBrush.ImageSource>
        </ImageBrush>
    </Border.Background>
</Border>

I need to "round the corners" of the hyperlinked image (WPF/XAML), probably combining aforementioned techniques. Thanks and regards,

Note: I've accepted the answer posted by user @lisp with just minor fix: Border background color should match the surrounding color in order to avoid slight "color leakage". Kudos to the author!

On a separate note: it was an eye-opening experience on how relatively difficult it is to achieve such simple effect while using WPF/XAML comparing to HTML5/CSS3 (see for, example, essentially the same effect on rounded corner image at: http://infosoft.biz/SlideShowCSS.aspx). It seems like WPF folks at Microsoft should take a note...

Was it helpful?

Solution

Border is used for rounded corners. But in your case if you simply put TextBlock inside of Border, you wouldn't get the desired effect. Here Corners are made transparent using a border. Grid is used so that Border stretches exactly to the size of TextBlock.

<Grid>
    <Border Name="CornersMask" Background="White" CornerRadius="20"/>
    <TextBlock>
        <TextBlock.OpacityMask>
            <VisualBrush Visual="{Binding ElementName=CornersMask}"/>
        </TextBlock.OpacityMask>
        <Hyperlink ...>
            <Image Name="someName" Source="some url" />
        </Hyperlink>
    </TextBlock>
</Grid>

TextBlock is displayed on top of Border, and because of that and antialiasing you may experience slight whiteness on the rounded edges. Either change the Border background to the surrounding background color, or enclose Border in another container that will autostretch it e.g. Border of Grid, and set it's Visibility to Hidden.

<Border Visibility="Hidden">
    <Border Name="CornersMask" Background="White" CornerRadius="20"/>
</Border>

This also solves the problem when the surrounding background is not a SolidColorBrush

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top