4

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...

4

1 回答 1

6

边框用于圆角。但是在您的情况下,如果您只是将 TextBlock 放在 Border 内,您将无法获得所需的效果。在这里,使用边框使角变得透明。使用 Grid 以便 Border 精确地拉伸到 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 显示在 Border 的顶部,正因为如此和抗锯齿,您可能会在圆角边缘遇到轻微的白度。要么将边框背景更改为周围的背景颜色,要么将边框包含在另一个容器中,该容器将自动拉伸它,例如网格边框,并将其可见性设置为隐藏。

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

这也解决了周围背景不是SolidColorBrush时的问题

于 2013-05-13T12:18:30.153 回答