Edward Tanguay
Edward Tanguay

Reputation: 193302

How to incorporate Canvas into a larger layout in WPF?

Canvas doesn't seem to play well together nicely with the other elements when you try to build it into a layout and have e.g. controls on the side and the canvas is the drawing area.

For instance, why can I put a border around every element except a canvas? In the following code, border wraps canvas but the canvas only has the border on the top but not on the left, right or bottom:

<Window x:Class="WpfApplication25.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <StackPanel>

        <TextBlock DockPanel.Dock="Bottom" Text="Move the slider to reveal the answer:"/>
        <Slider DockPanel.Dock="Bottom" Name="theSlider" 
            HorizontalAlignment="Left" 
            Width="200" 
            Minimum="0" 
            Maximum="1" 
            Value="1" 
            Cursor="Hand"/>

        <Border BorderBrush="Tan" BorderThickness="2">
            <Canvas>
                <TextBlock Canvas.Left="45" Canvas.Top="50" Text="test" FontSize="16"/>
                <Rectangle 
                    Canvas.Left="10" 
                    Canvas.Top="10" 
                    Width="100" 
                    Height="100" 
                    Fill="Silver" 
                    Opacity="{Binding ElementName=theSlider, Path=Value}"
                    />
            </Canvas>
        </Border>
    </StackPanel>
</Window>

Upvotes: 1

Views: 1201

Answers (2)

Alan Mendelevich
Alan Mendelevich

Reputation: 3611

As far as I understand what you are trying to achieve, you should place your controls in one cell of a Grid and your Canvas in another.

Upvotes: 0

user7116
user7116

Reputation: 64068

From what I can tell in XamlPad, the problem appears to be that your Canvas does not have an explicit height/width, and that its HorizontalAlignment defaults to being in the middle of the Border. Without an explicit height and width the Border appears to collapse to 0 height and stretches on the width. My assumption is this is because your Border is in a StackPanel, as placing the Border in a Grid, causes it to behave as expected.

Your best bet is to give the Canvas an explicit Height and Width. Not sure that is what you're looking for though.

Upvotes: 1

Related Questions