C#添加带有图像和处理程序的按钮

本文关键字:处理 程序 按钮 图像 添加 | 更新日期: 2023-09-27 18:26:48

我有一个简单的问题,但由于这是我第一次使用C#/XAML,所以我就到此为止。

XAML文件包含一个StackPanel,我想在运行时向其添加可单击的图像。

<StackPanel x:Name="grid_" Orientation="Horizontal" Margin="10 0 10 0" VerticalAlignment="Center">
</StackPanel>

我没有成功地在这些图像上创建点击事件,我读到我可以尝试使用按钮,改变它们的背景。这是我的代码:

        for (int i = 0; i < 20; i++)
        {
            Button j = new Button();

            //Image j = new Image();
            //j.Source = new BitmapImage(new Uri("Images/my_thumb.png", UriKind.Relative));
            var brush = new ImageBrush();
            j.BackgroundImage = brush;
            //j.MouseDown += new RoutedEventHandler(this.changeImage);
            grid_.Children.Add(j);
            Grid.SetRow(j, i);    
        }

现在,我如何更改按钮图像,并添加一个处理程序来检索已单击的按钮?我得到的错误是

Error   3   'System.Windows.Controls.Button' does not contain a definition for 'BackgroundImage' and no extension method 'BackgroundImage' accepting a first argument of type 'System.Windows.Controls.Button' could be found (are you missing a using directive or an assembly reference?)

你可以从我在代码中的评论中看到,我仍然保留纯图像的方法,只是为了确定:如果你知道如何让我的图像可以点击,请告诉我:)

我可以确定一个事件处理程序,它可以只检索按钮图像源文件名,以防万一。

你能给我指正确的方向吗?记住,我是一个完全的新手!:)

谢谢!

C#添加带有图像和处理程序的按钮

您可以使用Click事件

j.Click += new EventHandler(onButtonClick);

然后在事件处理程序中

void onButtonClick(Object sender, EventArgs e)
{
    var clickedButton = sender as Button;
    // do your stuff..    
}

XAML

        <Button x:Name="button" Content="Button1" HorizontalAlignment="Left" Margin="400,20,0,0" VerticalAlignment="Top" RenderTransformOrigin="-1.258,-5" Click="Button_Click" Height="80" Width="80"/>

C#

    private void Button1_Click(object sender, RoutedEventArgs e)
    {
        button1.Background = new ImageBrush { ImageSource = new BitmapImage(new Uri("ms-appx:/Images/timerg.png", UriKind.RelativeOrAbsolute)) };
    }

或C#

    private void Button1_Click(object sender, RoutedEventArgs e)
    {
            BitmapImage bmp = new BitmapImage();
            Uri u = new Uri("ms-appx:/Images/timer.png", UriKind.RelativeOrAbsolute);
            bmp.UriSource = u;
            // NOTE: change starts here
            Image i = new Image();
            i.Source = bmp;
            button1.Content = i;
    }