C# 如何使用代码添加控件及控件事件

1.首先简单设计一下界面:
添加了Click事件

<Window x:Class="WpfApp.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:WpfApp"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <ScrollViewer VerticalScrollBarVisibility="Auto">
        <StackPanel Name="addButtonSp" Margin="5">
            <Button FontSize="20" Foreground="Blue" Click="OnButtonClick">在窗口加入按钮</Button>
        </StackPanel>
    </ScrollViewer>
</Window>

2.在代码部分,简单设计一下控件属性
就是在点击上面Button 按钮时,界面自动添加一个按钮

private void OnButtonClick(object sender, RoutedEventArgs e)
{
    Button btn = new Button();
    btn.Background = Brushes.LightBlue;
    btn.Foreground = Brushes.Yellow;
    btn.Height = 50;
    btn.Content = "按钮";
    btn.Click += new RoutedEventHandler(mes);
    addButtonSp.Children.Add(btn);
}

重点来了,
btn.Click += new RoutedEventHandler(mes);
这行代码,就是用来指定所添加的button控件的点击事件,必须要用RoutedEventHandler(),其次()里面是被调用的事件函数,请往下看:
private void mes(object sender, RoutedEventArgs e),注意参数写法

private void mes(object sender, RoutedEventArgs e)
{
    MessageBoxResult a = MessageBox.Show("你点击了?", "Tip",MessageBoxButton.YesNoCancel,MessageBoxImage.Error);
    if (a == MessageBoxResult.Yes)
    {
        MessageBox.Show("你又点击了?", "haha", MessageBoxButton.OK, MessageBoxImage.Exclamation);
    }
}
这部分的全部代码
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void OnButtonClick(object sender, RoutedEventArgs e)
    {
        Button btn = new Button();
        btn.Background = Brushes.LightBlue;
        btn.Foreground = Brushes.Yellow;
        btn.Height = 50;
        btn.Content = "按钮";
        btn.Click += new RoutedEventHandler(mes);
        addButtonSp.Children.Add(btn);
    }

    private void mes(object sender, RoutedEventArgs e)
    {
        MessageBoxResult a = MessageBox.Show("你点击了?", "Tip",MessageBoxButton.YesNoCancel,MessageBoxImage.Error);
        if (a == MessageBoxResult.Yes)
        {
            MessageBox.Show("你又点击了?", "haha", MessageBoxButton.OK, MessageBoxImage.Exclamation);
        }
        else if(a == MessageBoxResult.No)
        {
            this.Close();
        }
    }

3.结果
a.启动界面

b.疯狂加入按钮

c.随机点击一个按钮

添加button控件,再通过此控件调用其它函数,成功了O(∩_∩)O哈哈~

花絮:
其实,在实验二 图层操作.pdf中,老师给的代码就用了这个代码(>‿◠)✌

posted @   槑孒  阅读(1895)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
点击右上角即可分享
微信分享提示