How do I get the height and width from a DockPanel?

652 Views Asked by At

I am using a DockPanel to host some image enhancement controls. The image to be enhanced is in the 'center' dock position. I would like to have the image fill the entire area of the DockPanel. I have a custom class that implements the WPF Canvas control and takes a windows.Rect as input. This Rect will set the area for the image render function which I have overridden.

I have tried to get the DockPanel.ActualHeight and .ActualWidth. both are NaN and the DockPanel.Width and Height = 0.

    public MainWindow()
    {
        ImageDataModel = new ImageDataModel();
        DataContext = ImageDataModel;
        InitializeComponent();
        WindowState = WindowState.Maximized;
        var tmpWindow = Window.GetWindow(BaseDockPanel);
        Rect rect = new Rect(0, 0, BaseDockPanel.ActualWidth, BaseDockPanel.ActualHeight);
        bitmapCanvas = new BitMapCanvas(rect);
        BaseDockPanel.Children.Add(bitmapCanvas);
    }

I would like to be able to create a windows.Rect that is the actual dimension of the DockPanel.center height and width. Currently the height and width for the control are 0.

1

There are 1 best solutions below

0
IvanJazz On BEST ANSWER

At the point of the construction of MainWindow, the child controls within the Window, in your case BaseDockPanel has not been loaded yet.

That is why you're getting a 0 for it's ActualWidth and ActualHeight.

What you can do is add an EventHandler for the Window's Loaded event as shown below.

public MainWindow()
{
    ImageDataModel = new ImageDataModel();
    DataContext = ImageDataModel;
    InitializeComponent();
    WindowState = WindowState.Maximized;

    this.Loaded += Window_Loaded;
}

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    var tmpWindow = Window.GetWindow(BaseDockPanel);
    // You will get your ActualWidth and ActualHeight here.
    Rect rect = new Rect(0, 0, BaseDockPanel.ActualWidth, BaseDockPanel.ActualHeight);
    bitmapCanvas = new BitMapCanvas(rect);
    BaseDockPanel.Children.Add(bitmapCanvas);
}