Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Canvas.ActualWidth zero, even after loading

I cannot get ActualWidth of a canvas to any nonzero value. I simplified the real scenario and devoted a new WPF Application in VS to getting a nonzero value (and understanding). Unfortunately, I'm only getting zero. I feel like I'm missing some basic WPF understanding: I'm not that familiar with WPF.

I copied the MDSN demo, modified it slightly and I now have

public partial class MainWindow : Window {

private Canvas myCanvas;
public MainWindow()
{
    InitializeComponent();
    CreateAndShowMainWindow();
}
private void CreateAndShowMainWindow()
{
    // Create a canvas sized to fill the window
    myCanvas = new Canvas();
    myCanvas.Background = Brushes.LightSteelBlue;

    // Add a "Hello World!" text element to the Canvas
    TextBlock txt1 = new TextBlock();
    txt1.FontSize = 14;
    txt1.Text = "Hello World!";
    Canvas.SetTop(txt1, 100);
    Canvas.SetLeft(txt1, 10);
    myCanvas.Children.Add(txt1);

    // Add a second text element to show how absolute positioning works in a Canvas
    TextBlock txt2 = new TextBlock();
    txt2.FontSize = 22;
    txt2.Text = "Isn't absolute positioning handy?";
    Canvas.SetTop(txt2, 200);
    Canvas.SetLeft(txt2, 75);
    myCanvas.Children.Add(txt2);

    Grid content = new Grid();
    content.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
    content.Children.Add(myCanvas);
    this.Content = content;
    this.Loaded += MainWindow_Loaded;
}

void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
    var canvasRenderWidth = myCanvas.RenderSize.Width;
    var canvasActualWidth = myCanvas.ActualWidth;
} //place breakpoint here

I expect the canvas to have the same ActualWidth as the textbox after loading, but at the specified breakpoint, it's zero. Notice that the textboxes are visible when running the code above.

Can someone tell me how to make myCanvas.ActualWidth to automatically become the textbox.ActualWidth or tell me why this shouldn't be done?

In my real usage scenario I've got a Canvas in a in column of a Grid, where the columndefinition's width is set to auto, so I expected it to increase as the canvas' width increases. However, this fails, and I suspect it's due to the canvas.ActualWidth being zero.

like image 838
JBSnorro Avatar asked Oct 20 '22 11:10

JBSnorro


1 Answers

Remove this line, and it will work:

content.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });

Note: The canvas is never resizing itself to fit it's content. The reason why the Text is visible in your example, is that the canvas is not clipping it's content.

when you set

myCanvas.ClipToBounds = true;

the text will also disappear.

like image 199
SnowballTwo Avatar answered Oct 23 '22 03:10

SnowballTwo