tags:

views:

502

answers:

2

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>
+1  A: 

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.

sixlettervariables
Yes, I gave it a height and width and then the border is around the canvas but with an odd margin. It just seems that canvas has an odd relationship with the other elements, would like to see an example of Canvas being used in WPF with controls on the side, etc.
Edward Tanguay
A: 

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.

Alan Mendelevich