Reputation: 45
private void Hangman_OnLoaded()
{
const int btnSize = 25;
for (var i = 65; i <= 90; i++)
{
var btn = new Button { Content = (char)i };
btn.Width = btn.Height = btnSize;
var margin = btn.Margin;
margin.Left += btnSize + 100;
btn.Margin = margin;
GridMain.Children.Add(btn);
}
}
So, I have this code block and i want to create alphabet with ASCII. I have a Grid named GridMain. I want to display A-Z. When I debug, I see that buttons are created in one nest. What should I use to display these letters next to each other?
Upvotes: 3
Views: 158
Reputation: 3923
Since these are buttons, that has single character ( atleast based on your question ), The size of the items will always be the same. So i would suggest you to use GridView with DataTemplate to load ASCII Characters as Buttons.
change your Hangman_OnLoaded
to below.
private void Hangman_OnLoaded()
{
List<char> bindingData = new List<char>();
for (var i = 65; i <= 90; i++)
{
bindingData.Add((char)i);
}
variableGrid.DataContext = bindingData;
}
Below will be your GridView.
<GridView x:Name="variableGrid" ItemsSource="{Binding }">
<GridView.ItemTemplate>
<DataTemplate>
<Button Content="{Binding ''}" />
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
Upvotes: 3
Reputation: 37066
If you insist on doing everything in code behind for the usual reasons, that would look more like this:
var GridMain = new System.Windows.Controls.Primitives.UniformGrid
{
Name = "GridMain",
Rows = 10,
Columns = 10
};
If for some reason you really want to use Grid
, you need to define rows and columns in the Grid
and set the row and column values on each Button
.
XAML
<Grid x:Name="GridMain">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<!-- etc. however many rows -->
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<!-- etc. however many columns -->
</Grid.ColumnDefinitions>
</Grid>
C#:
// Row zero, column zero
Grid.SetRow(btn, 0);
Grid.SetColumn(btn, 0);
Etc.
If this were WPF (it isn't, but maybe somebody doing WPF will click on this some day), your best, simplest solution is to use UniformGrid
instead of regular Grid
, and set the correct number of rows and columns on it:
<UniformGrid x:Name="GridMain" Rows="10" Columns="10">
</UniformGrid>
VariableSizedWrapGrid
might be an acceptable UWP substitute for UniformGrid
in your case, but I'm on Win7 here and can't test it.
Upvotes: 0