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

前端 未结 3 1604
北海茫月
北海茫月 2021-02-05 02:45

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:



        
相关标签:
3条回答
  • 2021-02-05 02:49

    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.

    0 讨论(0)
  • 2021-02-05 02:57

    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>
    
    0 讨论(0)
  • 2021-02-05 03:15

    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>
    
    0 讨论(0)
提交回复
热议问题