0

I am trying to get the inner canvas width and height at runtime, but I always get the same result. Here is my simple code:

MainWindow.xaml:

<Window 
...
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Viewbox>
            <Canvas Width="500" Height="300" Background="Red">
                <Canvas Width="200" Height="200" Background="Green" Name="innerCanvas">
                </Canvas>
            </Canvas>
        </Viewbox>
        <Button Click="Button_Click" Height="30" VerticalAlignment="Bottom" Content="Click"></Button>
    </Grid>
</Window>

MainWindow.cs:

private void Button_Click(object sender, RoutedEventArgs e)
{
    MessageBox.Show($"width: {innerCanvas.ActualWidth}, height: {innerCanvas.ActualHeight}");
}

Despite resizing the window at runtime, the messageBox prints 200x200

3SAT
  • 109
  • 3
  • Same as here: https://stackoverflow.com/q/73019528/1136211. Setting Width and Height enforces the requested size. – Clemens Jul 23 '22 at 08:06
  • @Clemens This does not solve my problem, because I need to set the inner grid's initial width and height – 3SAT Jul 23 '22 at 08:14
  • It is unclear what exactly your problem is, or why you have this layout at all. But as said, as soon as you set Width and Height, ActualWidth and ActualHeight will return those values. – Clemens Jul 23 '22 at 09:47
  • This may be helpful: https://stackoverflow.com/q/2119723/1136211 – Clemens Jul 23 '22 at 10:31

0 Answers0