Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I put a border around an image in WPF?

Tags:

wpf

xaml

I have a StackPanel containing five images and I want to put a black border around each image.

The XAML I have at the moment is:

<Image Name="imgPic1"
       Width="100"
       Height="75"
       Stretch="Fill"
       VerticalAlignment="Top" />

I thought I would be just able to put a one-unit margin or padding on the image and set a background color to 000000 but Padding and Background are both invalid for images.

What is an easy way to do this in XAML? Do I really have to put each image inside another control to get a border around it or is there some other trickery I can use?

like image 733
paxdiablo Avatar asked Jun 22 '10 12:06

paxdiablo


People also ask

How do I add a border in WPF?

To place a border around an element, WPF provides the Border element. Similar to other WPF elements, the Border has Width, Height, Background, and HorizontalAlignment and VerticalAlignment properties. Besides these common properties, Border has two properties that make Border a border.

How do you add a border in XAML?

To apply a border to a XAML element, you can place the element within a Border element, The BorderThickness and BorderBrush are two main properties of a Border The BorderBrush property represents the brush that is used to draw the border. The BorderThickness property represents the thickness of the border.

How do you make a grid border in WPF?

Need to add Grid. ColumnSpan="the columns you want to cover" Grid. RowSpan= "The rows you want to cover" in Border tag. Otherwise it only covers the first cell.


2 Answers

Simply wrap the Image in a Border control

<Border BorderThickness="1">     <Image Name="imgPic1"            Width="100"            Height="75"            Stretch="Fill"            VerticalAlignment="Top" /> </Border> 

You could also provide a style you apply to images that does this if you don't want to do it around every image


Final solution from answer and comments added by Pax:

<Border BorderThickness="1"         BorderBrush="#FF000000"         VerticalAlignment="Top">     <Image Name="imgPic1"            Width="100"            Height="75"            Stretch="Fill"            VerticalAlignment="Top"/> </Border> 
like image 117
Craig Suchanec Avatar answered Sep 21 '22 23:09

Craig Suchanec


The accepted answer will not work because of the problem described here https://wpf.2000things.com/2011/04/17/279-adding-a-border-around-an-image-control/

I solved it this way.

<Viewbox>
    <Border BorderThickness="3" BorderBrush="Red">
     <Image Stretch="None" ></Image>
    </Border>
   </Viewbox>
like image 37
Andreas Avatar answered Sep 23 '22 23:09

Andreas