Moses Aprico
Moses Aprico

Reputation: 2121

Keeping track of auto-height-row's ActualHeight in VM

Sorry if any of code below is not well-formatted. I post it from my phone because my wifi is having trouble at the moment.

I want to be able to make something like this (I know that it's not possible this way):

...
<RowDefinition Height="Auto" ActualHeight="{Binding RowHeight, Mode="OneWayToSource"}"/>
...

So, basically the height is auto (because the possible number of the items (e.g. Label) in it is 0-n - using ItemsControl representation), but I need to know the exact height of the item control (in this case, it's the row) to calculate the number of "pages" needed to represent my data. Just like pages in ms word.

Naming the row (theRow.ActualHeight), however, is not possible since VM / MVVM in general shouldn't be done that way (I don't have direct access to the view anyway)

Any idea how to do it? Thanks.

Upvotes: 1

Views: 149

Answers (1)

Kcvin
Kcvin

Reputation: 5163

This is what I have, and it seems to work. Also, I have copied the SizeObserver found in this post:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <TextBlock Text="This is row 1" Grid.Row="0"></TextBlock>
    <ItemsControl Grid.Row="1" 
                  vm:SizeObserver.Observe="True" 
                  vm:SizeObserver.ObservedHeight="{Binding ActHeight, Mode=OneWayToSource}">
        <TextBlock Text="1"></TextBlock>
        <TextBlock Text="2"></TextBlock>
        <TextBlock Text="3"></TextBlock>
        <TextBlock Text="4"></TextBlock>
        <TextBlock Text="5"></TextBlock>
        <TextBlock Text="6"></TextBlock>
    </ItemsControl>
    <TextBlock Text="This is row 3"
               Grid.Row="2"></TextBlock>
</Grid>

In my view model:

public double ActHeight
{
    get
    {
        return _height;
    }
    set
    {
        _height = value;
    }
}

Because ItemsControl is the only element in Row 1, we know that the row definition, or height of the row will be the actual height of the control inside the row--the ItemsControl.

Upvotes: 1

Related Questions