views:

144

answers:

2

I have a custom control that I've placed inside a cell of a grid. I have some internal calculations I need to run based on the height and width of the custom control. However, I want it to resize based on the size of the cell.

So, my main question is... how to I programatically determine the height and width of a given cell?

+1  A: 

It may be easier to figure out the Height and Width of your Custom Control rather than the cell of a DataGrid.

Your control should have access (through FrameWork Element) to the properties ActualHeight and ActualWidth. These properties will update when the size changes.

Also, the SizedChanged event will be fired on your control every time the Height and Width change.

I highly recommend placing this height and width logic inside of your control. You do not want to be limited to only placing your custom control inside of DataGrids.

private void UserControl_SizeChanged(object sender, System.Windows.SizeChangedEventArgs e)
{
    HeightBox.Text = this.ActualHeight.ToString();
}
Jeremiah
I guess what I'm trying to do (or been asked of me to do) is to be able to a) specify a size or b) allow the size to adjust to the container. For instance, a button... you can give it a size or let its size be dictated by it's container. That's what I'm going for. I derived one of my controls from a ListBox and that works fine in a grid when I do not specify the size. The other control derives from Control and is composed of a ScrollViewer (and some canvases). Dropping a ScrollViewer itself in a grid cell gives me the behavior I expect but my custom control behaves differently.
beaudetious
So, if I know the size of the cell, I can at least set the size of my custom control in code whenever it's resized.
beaudetious
Jeremiah! I could kiss you but that would be a) impossible via StackOverflow and b) kind of gross. My original code was working fine except I was using this.Width instead of this.ActualWidth, etc.Thanks for restoring my faith in the StackOverflow community.
beaudetious
You're most welcome!
Jeremiah
A: 

You can get size of grid cell through RowDefinitions and ColumnDefinitions:

MyGrid.RowDefinitions[1].ActualHeight
MyGrid.ColumnDefinitions[1].ActualWidth

but it should be pretty rare situation then you have to resort to this kind of approach

Denis