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?
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.
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.
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.
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With