Dynamically creating buttons in Windows Phone 8.1

I created the application in Windows Phone 8.1 (universal). I need to create a dynamic button field. This is my xaml example:

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

      <Grid x:Name="_root"
          Grid.Row="1"
          Margin="10" />

This is my code:

            _root.Children.Clear();
            _root.ColumnDefinitions.Clear();
            Size = 5;
            for (int i = 0; i < Size; i++)
            {
                _root.ColumnDefinitions.Add(new ColumnDefinition
                {
                    Width = new GridLength(1, GridUnitType.Star)
                });
            }
                for (int column = 0; column < Size; column++)
                {
                    Button btnTemp = new Button();
                    btnTemp.Visibility = Visibility.Visible;
                    btnTemp.VerticalAlignment = VerticalAlignment.Stretch;
                    btnTemp.HorizontalAlignment = HorizontalAlignment.Stretch;
                    btnTemp.HorizontalContentAlignment = HorizontalAlignment.Center;
                    btnTemp.VerticalContentAlignment = VerticalAlignment.Center;
                    btnTemp.BorderBrush = new SolidColorBrush(Colors.Blue);
                    btnTemp.Content = column;
                    Grid.SetColumn(btnTemp, column);
                    Grid.SetRow(btnTemp, 0);
                    _root.Children.Add(btnTemp);    
                }

This is my result:

enter image description here

If I used:

  Width = new GridLength(1, GridUnitType.Auto)

I get the result:

enter image description here

I need to fix these errors:

1. Enter the text in the center of the button.

  1. Do not see the right border of the "4" button. Buton "4" is another wide.
+4
source share
1 answer

The fix in your case is quite simple - just define the MinWidth of the created button as 0(the default value has some value).

btnTemp.MinWidth = 0;

I think this should help.

, , , , ItemsPanel ItemsTemplate Button, .

+3

Source: https://habr.com/ru/post/1615864/


All Articles