title: How to programmatically maintain aspect ratio of object in wpf
body: <p>I programmatically add a <code>Border</code> with a certain width and height to a grid. However, I want to get either one of the following:</p>
  
  <ol>
  <li>Make the border keep aspect ratio and fill make it as big as possible inside the grid</li>
  <li>Make the border scale whenever the grid scales down or up (so not particularily the biggest possible, more like a percentage of the grid)</li>
  </ol>
  
  <p>At the moment this is the situation when I resize my window:</p>
  
  <pre><code>Color borderColor = (Color)ColorConverter.ConvertFromString(BorderColor);
  Color backgroundColor = (Color)ColorConverter.ConvertFromString(BackgroundColor);
  
  Border border = new Border();
  border.BorderThickness = new Thickness(BorderSize);
  border.CornerRadius = new CornerRadius(TopLeftCornerRadius, TopRightCornerRadius, BottomRightCornerRadius, BottomLeftCornerRadius);
  border.BorderBrush = (SolidColorBrush)(new BrushConverter().ConvertFrom(BorderColor));
  border.Background = (SolidColorBrush)(new BrushConverter().ConvertFrom(BackgroundColor));
  
  border.Width = Width;
  border.Height = Height;
  
  border.Margin = new Thickness(10);
  
  previewgrid.Children.Add(border);
  </code></pre>
  
  <p>The normal situation:</p>
  
  <p><a href="https://i.stack.imgur.com/0KSJY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0KSJY.png" alt="enter image description here"></a></p>
  
  <p>The scaled situation:</p>
  
  <p><a href="https://i.stack.imgur.com/3PpUT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3PpUT.png" alt="enter image description here"></a></p>
  
  <p>So I would like it to resize properly and stay inside the white rectangle. By the way, the white grid has a margin as you can see ;-)
  Thanks in advance!</p>