【问题标题】:How to create objects dynamically with arbitrary names?如何使用任意名称动态创建对象?
【发布时间】:2011-02-18 07:30:21
【问题描述】:

这就是我的情况。我正在设计一个程序,当用户单击某个按钮时,该程序需要在画布上实时创建新的图像对象。由于我不知道任何给定用户将创建多少所述图像,因此我无法在代码中为每个图像分配名称。图片需要命名为“Image0”、“Image1”、“Image2”等,具体取决于页面上已经存在的图片数量。有点像 Visual Studio 本身的工作方式,每次将控件拖放到设计视图时,它都会自动在控件名称后附加一个数字。

有没有人有可以执行这个功能的代码sn-p?

【问题讨论】:

  • 可以不使用集合吗(例如List<YourImageType>)?
  • 也许吧。那仍然允许图像拥有/使用事件吗?如何更改列表中图像的属性或响应用户交互?
  • 确保您可以附加任何事件处理程序并在将新创建的控件添加到列表之前为其设置任何属性:)

标签: c# silverlight visual-studio-2010


【解决方案1】:

您不必明确命名所有控件。只需将它们添加到画布“控件”列表即可。

使用单个按钮和 flowLayoutPanel 创建一个 Windows 应用程序。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication6
{
    public partial class Form1 : Form
    {
        int i = 1;
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var button = new Button { Text = string.Format("Button {0}", i) };
            button.Click += new EventHandler(button_Click);
            flowLayoutPanel1.Controls.Add(button);
            i += 1;
        }

        void button_Click(object sender, EventArgs e)
        {
            Button button = (Button)sender;
            button.Text = " clicked!";
        }
    }
}

【讨论】:

  • 是的!我将代码改编为图像而不是按钮,并且效果很好!谢谢!现在,如果我需要编辑该控件的属性,我该怎么办?比如,如果我想稍后更改按钮的文本?
【解决方案2】:

我没有直接回答您的问题,但从它的声音来看,我可能是错的,因为我不知道您要做什么,您是从新手那里查看问题程序员视角。您可能需要考虑使用某种集合(可能是列表)并动态地将图像对象添加到其中。如果您想要一个与每个对象关联的字符串名称,您可以考虑使用 Dictionary<string,Image> 类型的字典

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-21
    • 2011-07-25
    • 2014-06-07
    • 1970-01-01
    • 2017-04-06
    • 1970-01-01
    • 2015-11-27
    • 1970-01-01
    相关资源
    最近更新 更多