31.九个按钮排列 C#例子 WPF例子
一个3*3共9个按钮的WPF例子,进行简单的操作,使其正常排列并返回消息。
C#代码
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace practice
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
// 获取被点击的按钮并显示其内容
//引入一个变量名获取点击的这个按钮的属性
Button buttonclicked = (Button)sender;
//调用这个按钮的属性,也就是按钮的内容
MessageBox.Show($"按钮{buttonclicked.Content}被按下了", "按钮按下提示");
}
}
}
XMAL代码:
<Window x:Class="practice.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:practice"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="300">
<Grid>
<UniformGrid Rows="3" Columns="3" Margin="60">
<Button Content="1" Click="Button_Click"/>
<Button Content="2" Click="Button_Click"/>
<Button Content="3" Click="Button_Click"/>
<Button Content="4" Click="Button_Click"/>
<Button Content="5" Click="Button_Click"/>
<Button Content="6" Click="Button_Click"/>
<Button Content="7" Click="Button_Click"/>
<Button Content="8" Click="Button_Click"/>
<Button Content="9" Click="Button_Click"/>
</UniformGrid>
</Grid>
</Window>