Totty
Totty

Reputation: 916

How can you align a canvas background in WPF?

I have set a canvas' background to an image of a company logo. I would like for this image to be aligned to the bottom right corner of the canvas.
Is it possible to do this, or would it require for the image to be added into the canvas as a child? That would not work with this program as all children of the canvas are handled differently.

Thank You

Upvotes: 6

Views: 10901

Answers (4)

Enrique Marco
Enrique Marco

Reputation: 1

This is my solution using a border inside the canvas to align the image. This solution works well when canvas is resized:

<Canvas x:Name="MiCanvas" Height="250" Width="500" Background="Aqua">
    <Border x:Name="MiBorderImage" 
            Width="{Binding ElementName=MiCanvas, Path=ActualWidth}"
            Height="{Binding ElementName=MiCanvas, Path=ActualHeight}"
            Background="Transparent">
        <Image x:Name="MiImage" Source="/GraphicsLibrary/Logos/MiLogo.png"
               HorizontalAlignment="Right" 
               VerticalAlignment="Bottom" 
               Stretch="None" />
    </Border>
 </Canvas>

Upvotes: 0

Ryan Lundy
Ryan Lundy

Reputation: 210140

Will this work? (It worked for me, anyway.)

  <Canvas>
    <Canvas.Background>
      <ImageBrush ImageSource="someimage.jpg" AlignmentX="Right" 
          AlignmentY="Bottom" Stretch="None" />
    </Canvas.Background>
  </Canvas>

Upvotes: 16

Alan Le
Alan Le

Reputation: 8833

How about containing the canvas and image inside of a Grid control like so?

<Window ...>
  <Grid>
    <Canvas/>
    <Image HorizontalAlignment="Right" VerticalAlignment="Bottom" .../>
  <Grid>
</Window>

Upvotes: 0

Gishu
Gishu

Reputation: 136613

AFAIK The WPF Canvas needs child UI elements to be positioned using absolute co-ordinates. To achieve the right-bottom-anchored effect, I think you'd need to handle the window resize event, recalculate and apply the Top,Left co-ordinates for the child Image element to always stick to the right buttom corner.

<Window x:Class="HelloWPF.Window1" xmlns...
    Title="Window1" Height="300" Width="339">
    <Canvas>
        <Image Canvas.Left="195" Canvas.Top="175" Height="87" Name="image1" Stretch="Fill" Width="122" Source="dilbert2666700071126ni1.gif"/>
    </Canvas>
</Window>

Upvotes: 0

Related Questions