为位于网格单元格中的每个按钮动态分配点击事件
Dynamically assign a click event to every single button located in a grid cell
我一直在研究 Xamarin Forms 应用程序 (UWP)。
我想动态地将点击事件分配给位于网格内的每个单元格。
目标是处理每个按钮的鼠标右键单击,以便
相关按钮的背景颜色发生变化。
我见过与 ObservableCollection 相关的解决方案。
但是,我很好奇是否可以执行
提到的任务而不使用它。
我的意思是写一个单一的事件方法定义,它能够
感应用户点击的按钮。
这是我想象中的代码布局 (#c):
for (int i = 0; i < _lattice.Size; i++) //Add rows
{
ColumnDefinition columna = new ColumnDefinition();
columna.Width = new GridLength(25);
_gamePage._gameGrid.ColumnDefinitions.Add(columna);
}
for (int i = 0; i < _lattice.Size; i++) //Add columns
{
RowDefinition row = new RowDefinition();
row.Height = new GridLength(25);
_gamePage._gameGrid.RowDefinitions.Add(row);
}
for (int i = 0; i < _lattice.Size; i++)
{
for (int j = 0; j < _lattice.Size; j++)
{
Button but = new Button();
but.BorderColor = Color.LightGray;
but.BorderWidth = 2;
but.HorizontalOptions = LayoutOptions.Center;
but.VerticalOptions = LayoutOptions.Center;
//Assigning click event
but.Clicked += ButtonClicEvent;
_lattice.ButtonLattice[j * _lattice.Size + i] = but;
Grid.SetRow(but, i);
Grid.SetColumn(but, j);
GamePage._gameGrid.Children.Add(but); //Add the desired button to the grid
}
}
每个 C# 事件处理程序都有一个 sender 参数,它是对触发事件的对象的引用
protected void ButtonClicEvent(object sender, EventArgs e)
{
var btn = (Button)sender;
// btn is a reference to the button that fired the event
btn.BackgroundColor = Color.Orange;
}
我一直在研究 Xamarin Forms 应用程序 (UWP)。
我想动态地将点击事件分配给位于网格内的每个单元格。 目标是处理每个按钮的鼠标右键单击,以便 相关按钮的背景颜色发生变化。 我见过与 ObservableCollection 相关的解决方案。 但是,我很好奇是否可以执行 提到的任务而不使用它。
我的意思是写一个单一的事件方法定义,它能够 感应用户点击的按钮。
这是我想象中的代码布局 (#c):
for (int i = 0; i < _lattice.Size; i++) //Add rows
{
ColumnDefinition columna = new ColumnDefinition();
columna.Width = new GridLength(25);
_gamePage._gameGrid.ColumnDefinitions.Add(columna);
}
for (int i = 0; i < _lattice.Size; i++) //Add columns
{
RowDefinition row = new RowDefinition();
row.Height = new GridLength(25);
_gamePage._gameGrid.RowDefinitions.Add(row);
}
for (int i = 0; i < _lattice.Size; i++)
{
for (int j = 0; j < _lattice.Size; j++)
{
Button but = new Button();
but.BorderColor = Color.LightGray;
but.BorderWidth = 2;
but.HorizontalOptions = LayoutOptions.Center;
but.VerticalOptions = LayoutOptions.Center;
//Assigning click event
but.Clicked += ButtonClicEvent;
_lattice.ButtonLattice[j * _lattice.Size + i] = but;
Grid.SetRow(but, i);
Grid.SetColumn(but, j);
GamePage._gameGrid.Children.Add(but); //Add the desired button to the grid
}
}
每个 C# 事件处理程序都有一个 sender 参数,它是对触发事件的对象的引用
protected void ButtonClicEvent(object sender, EventArgs e)
{
var btn = (Button)sender;
// btn is a reference to the button that fired the event
btn.BackgroundColor = Color.Orange;
}