Search code examples
c#wpfviewbox

Viewbox is greyed out when the window opens


I had a UniformGrid that I filled with buttons but wanted the content to change size with the window so I added a viewbox.

<Viewbox Grid.ColumnSpan="1" Stretch="Fill" Margin="250,67,250,67">
    <UniformGrid Name="grdButtons" Rows="15" Columns="15" Margin="0"/>
</Viewbox>
private void CreateButtons()
{
    for (int row = 0; row < 15; row++)
    {
        for (int col = 0; col < 15; col++)
        {
            Button btn = new Button();

            btn.Name = "btn" + row.ToString("00") + col.ToString("00");

            btn.Background = new SolidColorBrush(Colors.White);
            btn.Click += new RoutedEventHandler(Button_Click);

            grdButtons.Children.Add(btn);
        }
    }
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    ((Button)sender).Content = "O";
}

When the window opens the viewbox is greyed out until first button is clicked. After that it works as I wanted.

How do I avoid this?


Solution

  • When the UniformGrid was without size it seems the viewbox didn't know how to handle it. All I did was change "Margin=0" to "Width=300 Height=300" and it was fixed.

    <Viewbox Grid.ColumnSpan="1" Stretch="Fill" Margin="250,67,250,67">
        <UniformGrid Name="grdButtons" Rows="15" Columns="15" Width="300" Height="300"/>
    </Viewbox>