Zea Shah
Zea Shah

Reputation: 382

How to get height of an control in ViewModel

I have a ContentControl in my Xaml and I want to access it's Height in ViewModel, what I tried is created a property in my ViewModel and Bind that to ContentControl via TwoWay. But problem with that is it's setting ContentControl height to 0, which is the default value of that property.

Code:

Xaml

<ContentControl x:Name="ContentControl"
                Content="{Binding ContentFrame}"
                HorizontalContentAlignment="Stretch"
                Height="{Binding ContentControlHeight, Mode=TwoWay}"
                VerticalContentAlignment="Stretch"></ContentControl>

ViewModel(Had property change notification using Fody):

public double ContentControlHeight { get; set; }

Upvotes: 3

Views: 3635

Answers (2)

Xie Steven
Xie Steven

Reputation: 8611

Add to Romasz's suggestion, @ZeaShah you could make a custom class and register SizeChanged event in it.

public class MyContentControl : ContentControl
{
    public MyContentControl()
    {
        this.SizeChanged += MyContentControl_SizeChanged;
    }

    private void MyContentControl_SizeChanged(object sender, Windows.UI.Xaml.SizeChangedEventArgs e)
    {
        System.Diagnostics.Debug.WriteLine("SizeChanged: height " + e.NewSize.Height + " width: " + e.NewSize.Width);
        CHeight = e.NewSize.Height;
    }

    public double CHeight
    {
        get { return (double)GetValue(CHeightProperty); }
        set { SetValue(CHeightProperty, value); }
    }

    // Using a DependencyProperty as the backing store for CHeight.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty CHeightProperty =
        DependencyProperty.Register("CHeight", typeof(double), typeof(MyContentControl), new PropertyMetadata(0));
}

Defining a dependency property and binding it in your main page:

<local:MyContentControl x:Name="ContentControl"
            HorizontalContentAlignment="Stretch"
            VerticalContentAlignment="Stretch" CHeight="{Binding ContentControlHeight,Mode=TwoWay}">
</local:MyContentControl>

Upvotes: 4

Romasz
Romasz

Reputation: 29792

Binding to ActualHeight (and probably Width) is not a good choice, as:

For purposes of ElementName binding, ActualHeight does not post updates when it changes (due to its asynchronous and run-time calculated nature). Do not attempt to use ActualHeight as a binding source for an ElementName binding. If you have a scenario that requires updates based on ActualHeight, use a SizeChanged handler.

It's worth to follow the above and use SizeChanged event.

Upvotes: 3

Related Questions