WPF Auto height in code

C#WpfXaml

C# Problem Overview


How could I set the value of the Height property of a WPF control in C# code to "Auto"?

<Grid.RowDefinitions>
    <RowDefinition />
    <RowDefinition Height="Auto" />
    <RowDefinition />
    <RowDefinition Height="Auto" />
    <RowDefinition />
    <RowDefinition Height="Auto" />
    <RowDefinition />
    <RowDefinition Height="Auto" />
    <RowDefinition />
</Grid.RowDefinitions>

I want to reproduce this behavior in the code behind. Any ideas?

C# Solutions


Solution 1 - C#

Perhaps this link will help you.

> At times, you may want to > programmatically set the Height or > Width of a WPF element to Auto in > code. To do this, just use the > Double.NaN (Not a Number) value. > > For example, in C#: > > this.txtName.Width = Double.NaN;

Solution 2 - C#

You can use

RowDefinition rd = new RowDefinition();
rd.Height = GridLength.Auto;
ContentGrid.RowDefinitions.Add(rd);

Solution 3 - C#

While the question has been answered with the code-behind (as asked), here is the same solution in XAML for basic control properties who don't have "auto":

xmlns:sys="clr-namespace:System;assembly=mscorlib"

Height="{x:Static sys:Double.NaN}"

Posting because google took me here when searching for XAML solution for a TextBox (auto doesn't exist).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKarim AghaView Question on Stackoverflow
Solution 1 - C#Zach JohnsonView Answer on Stackoverflow
Solution 2 - C#Nimrod ShoryView Answer on Stackoverflow
Solution 3 - C#EdgarasView Answer on Stackoverflow