以下是一个示例代码,它使用.NET框架中的WPF技术,创建一个列表,并为每个列表项添加一个按钮。

MainWindow.xaml文件:

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <ListBox x:Name="listBox" HorizontalAlignment="Center" VerticalAlignment="Center">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding}" Margin="5"/>
                        <Button Content="Click" Click="Button_Click" Margin="5"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</Window>

MainWindow.xaml.cs文件:

using System.Collections.ObjectModel;
using System.Windows;

namespace WpfApp1
{
    public partial class MainWindow : Window
    {
        public ObservableCollection<string> Items { get; set; }

        public MainWindow()
        {
            InitializeComponent();

            Items = new ObservableCollection<string>
            {
                "Item 1",
                "Item 2",
                "Item 3"
            };

            listBox.ItemsSource = Items;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            // 按钮点击事件处理逻辑
            MessageBox.Show("Button clicked!");
        }
    }
}

这个示例创建了一个ListBox,其中的每个列表项都包含一个文本块和一个按钮。通过ItemTemplate属性,我们定义了每个列表项的外观,其中使用了一个StackPanel来水平排列文本块和按钮。

MainWindow.xaml.cs文件中,我们使用ObservableCollection来存储列表中的数据项,并将其赋值给ListBoxItemsSource属性。每个按钮都绑定到了同一个点击事件处理方法Button_Click,您可以在该方法中添加自定义的按钮点击逻辑

用net帮我写一个在列表中增加一个按钮的代码

原文地址: https://www.cveoy.top/t/topic/hFaH 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录