您好我需要帮助来切换两个按钮的内容
到目前为止我所做的是检查按钮是否是邻居。private int row = 4;
private int col = 4;
public MainWindow()
{
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Button cmd = (Button)sender;
MessageBox.Show(cmd.Tag.ToString());
string txt = cmd.Tag.ToString();
int r = int.Parse("" + txt[0]);
int c = int.Parse("" + txt[1]);
if (Math.Abs(r - row) + Math.Abs(c - col) == 1)
{
MessageBox.Show(r + " " + c);
}
我的XAML文件中的按钮就像这样
<Button Tag="00" Grid.Row="0" Grid.Column="0" Click="Button_Click">A</Button>
<Button Tag="01" Grid.Row="0" Grid.Column="1" Click="Button_Click">B</Button>
并且挑战是切换内容(A和B)
任何人都可以帮助我吗?
答案 0 :(得分:2)
Button_Click
方法那样使用WinForms事件处理。答案 1 :(得分:0)
只需使用临时变量来保存其中一个字符串。
string tmp = Button1.Text;
Button1.Text = Button2.Text;
Button2.Text = tmp;
答案 2 :(得分:0)
我会跳过通用的事件处理程序名称。您需要将要移动的按钮存储在临时变量中。
答案 3 :(得分:0)
我使用了九个按钮:
<Button Tag="00" Grid.Row="0" Grid.Column="0" Margin="15,21,13,23" Name="btn1" Click="btn1_Click">A</Button>
<Button Tag="01" Grid.Row="0" Grid.Column="1" Margin="15,21,13,23" Name="btn2" Click="btn1_Click">B</Button>
<Button Tag="02" Grid.Row="0" Grid.Column="2" Margin="15,21,13,23" Name="btn3" Click="btn1_Click">C</Button>
<Button Tag="10" Grid.Row="1" Grid.Column="0" Margin="15,21,13,23" Name="btn4" Click="btn1_Click">D</Button>
<Button Tag="11" Grid.Row="1" Grid.Column="1" Margin="15,21,13,23" Name="btn5" Click="btn1_Click">E</Button>
<Button Tag="12" Grid.Row="1" Grid.Column="2" Margin="15,21,13,23" Name="btn6" Click="btn1_Click">F</Button>
<Button Tag="20" Grid.Row="2" Grid.Column="0" Margin="15,21,13,23" Name="btn7" Click="btn1_Click">G</Button>
<Button Tag="21" Grid.Row="2" Grid.Column="1" Margin="15,21,13,23" Name="btn8" Click="btn1_Click">H</Button>
<Button Tag="22" Grid.Row="2" Grid.Column="2" Margin="15,21,13,23" Name="btn9" Click="btn1_Click">I</Button>
和此方法从网格和更改值中获取按钮:
private int row = 2;
private int col = 2;
private void btn1_Click(object sender, RoutedEventArgs args)
{
Button cmd = (Button)sender;
string txt = cmd.Tag.ToString();
int r = int.Parse("" + txt[0]);
int c = int.Parse("" + txt[1]);
if (Math.Abs(r - row) + Math.Abs(c - col) == 1)
{
MessageBox.Show(r + " " + c);
Button nearButton = grd1.Children.Cast<Button>().First(e => Grid.GetRow(e) == row && Grid.GetColumn(e) == col);
Object tmp = nearButton.Content;
nearButton.Content = cmd.Content;
cmd.Content = tmp;
}
}
在我的示例中,指定旁边的两个按钮用它来改变它们的值,希望这就是你想要的。
(通过X和Y从网格获取项目是从here)
中窃取的