首页 > 解决方案 > 打开一个动态创建的按钮时,所有按钮都打开

问题描述

我正在测试一个小应用程序,其中主窗口有一个输入文本框,用户单击添加(代码中的列表添加)并更新一个简单列表。除了列表更新之外,还将在包装面板中创建一个动态按钮。这个想法是用户然后可以单击他们需要更新的任何条目,并加载第二个窗口,该条目与列表中的索引相关联。

我有大部分工作的代码,但我对我认为微不足道的事情感到茫然。如果创建了 3 个按钮并且我点击按钮 3,它将弹出所有条目。所以三个带有指定索引的窗口。我只需要一个窗口来显示被点击的按钮。我玩过,这个特殊的问题正在逃避我。

我一直在寻找类似的答案,但在过去几天里出现了短缺。

主窗口:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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 TestApp
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        List<string> listA = new List<string>();

        private int x = 1;       
        private int t = 1;

        private void addBtn_Click(object sender, RoutedEventArgs e)
        {            
            listA.Add(listBx.Text);

            Button btns = new Button();
            btns.Width = 70;
            btns.Height = 30;
            btns.Content = "Button " + x;
            btns.Name = "Btn" + t;
            btns.Click += (s, t) =>
            {
                for (int index = 0; index < listA.Count; index++)
                {                    
                    EditWindow win = new EditWindow();
                    win.updateBx.Text = listA[index];
                    win.Show();                    
                }
            };
            btnPanel.Children.Add(btns);
            x++;
            t++;
        }

    }
}

第二个窗口(这里还没有代码,更新 btn 将重写与它相关的列表索引:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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.Shapes;

namespace TestApp
{
    /// <summary>
    /// Interaction logic for EditWindow.xaml
    /// </summary>
    public partial class EditWindow : Window
    {
        public EditWindow()
        {
            InitializeComponent();
        }

        private void updateBtn_Click(object sender, RoutedEventArgs e)
        {

        }

    }
}

标签: c#wpf

解决方案


我不熟悉 c#,但原因是我猜 click 函数中的循环。它按你说的做。而不是循环,您应该只使用当前的 listA 元素。


推荐阅读