paxdiablo
paxdiablo

Reputation: 882566

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

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?

Upvotes: 37

Views: 81750

Answers (3)

Andreas
Andreas

Reputation: 4013

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>

Upvotes: 10

Guy Cohen
Guy Cohen

Reputation: 767

I just stumbled upon this post and the other answer did not work right. Maybe because I now use framework 4 and this post is old?

In any case - if someone will see this by chance in the future - here is my answer:

 <Border Name="brdSiteLogo" 
          BorderThickness="2"
          BorderBrush="#FF000000"
          VerticalAlignment="Top"
          HorizontalAlignment="Left"
          Margin="12,112,0,0"
          Height="128" 
          Width="128">

     <Image Name="imgSiteLogo"             
         HorizontalAlignment="Stretch" 
         VerticalAlignment="Stretch" 
         Stretch="Fill"/>

  </Border>

The border thickness and brush are important (if you wont choose a color - you will not see the border!!!)

Also, the border should be aligned on your window. The image is "inside" the border, so you can use margins or just stretch it like I did.

Upvotes: 5

Craig Suchanec
Craig Suchanec

Reputation: 10834

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>

Upvotes: 71

Related Questions