Ali250
Ali250

Reputation: 662

Can't resize Canvas size using C#

Very simple issue: if I declare a canvas in XAML in a Windows Phone 8.1 app like so:

<Canvas x:Name="OptionsCanvas" Width="400" Height="450"  VerticalAlignment="Top" Background="White" PointerMoved="OptionsCanvas_PointerMoved">

It works fine, but I want to make my app adjust to phones with different screen sizes. So I'm getting the screen size using Window.Current.Bounds and setting the canvas dimensions as a ratio of the total screen size in c# in the page's constructor like so:

Point screenRes = new Point();
double scaleFactor = DisplayInformation.GetForCurrentView().RawPixelsPerViewPixel;
ScreenRes.X = Window.Current.Bounds.Width * scaleFactor;
ScreenRes.Y = Window.Current.Bounds.Height * scaleFactor;
MyCanvas.Width = ScreenRes.X * 0.5;
MyCanvas.Height = ScreenRes.Y * 0.7;

But this doesn't seem to be working. When I check the MyCanvas.ActualHeight and MyCanvas.ActualWidth properties after running the above code, both dimensions are zero and consequently, nothing shows in my canvas.

Upvotes: 0

Views: 855

Answers (1)

Łukasz Rejman
Łukasz Rejman

Reputation: 1892

I hope you know that Canvas doesn't clip its children. So even if its size is 0 x 0 all controls that are inside will be visible. I suggest you to use some different control to show the background that is more flexible, like Border and leave canvas as it is (with default 0 x 0 size). So your code could look like this:

<Border x:Name="OptionsBorder" 
        Width="400" 
        Height="450"  
        VerticalAlignment="Top" 
        Background="White" 
        PointerMoved="OptionsCanvas_PointerMoved">
    <Canvas x:Name="OptionsCanvas"
            VerticalAlignment="Top"
            HorizontalAlignment="Left" />
</Border>

So now you can change the size of OptionsBorder instead and don't care about canvas. Canvas has only one advantage - you can arrange your controls using Canvas.Left and Canvas.Top like X and Y.

Upvotes: 1

Related Questions