通过表单从用户控件访问 [英] Accessing from User Control via Form

查看:58
本文介绍了通过表单从用户控件访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

希望每个人都好,可以帮助一个新手吗?

我有一个我正在编写的C#应用​​程序.它具有一种形式(frmMainMenu),可从以下形式调用用户控件:

Hi All,

Hope everyone is well and can help a newbie with one?

I have a c# Application which iam writing. It has a form (frmMainMenu) which a user control is called from:

private void rtbResourceScheduling_Click(object sender, EventArgs e)
      {
          pnlMainMenu.Controls.Clear();
          ucResourceScheduling ui = new ucResourceScheduling();
          pnlMainMenu.Controls.Add(ui);
      }


在我的用户控件上,我有一个按钮(btnMonth):


On my User Control I have a button (btnMonth):

private void btnMonth_Click(object sender, EventArgs e)
       {
           calResourceScheduling.SelectedView = eCalendarView.Month;
       }


我的用户控件完整代码为:


My full code of the user control is:

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

namespace RMS.Client
{
    public partial class ucResourceScheduling : UserControl
    {
        public ucResourceScheduling()
        {
            InitializeComponent();
            CalendarModel _Model = new CalendarModel();
            calResourceScheduling.CalendarModel = _Model;
        }

        private void btnDay_Click(object sender, EventArgs e)
        {
            calResourceScheduling.SelectedView = eCalendarView.Month;
        }
     }
}


窗体和用户控件都在同一个名称空间中.我想摆脱用户控件上的按钮,并将其放置在主窗体中.


Both the Form and the user Control are in the same namespace. I want to get rid of the button on my User Control and have it on my Main Form.

private void btnDay_Click(object sender, EventArgs e)
        {
            calResourceScheduling.SelectedView = eCalendarView.Month;
        }


我该怎么办?

大家欢呼
SJG2004


How do I do this?

Cheers Everyone
SJG2004

推荐答案

您只需要摆脱按钮,并公开一些用于旧按钮Click处理程序中的方法即可. .看来这种方法的实现是在代码示例的最后一行编写的.



例如,在控件中,添加:
You simply need to get rid of the button and expose some method which you uses to use in the handler of the old button''s Click handler. It looks like the implementation of such method is written in the last line of your code sample.



For example, in the control, add:
class SomeUserControl : /* Control, UserControl, whatever */ {

//...

    public void SomeNewMethod() {
       // I'm not sure why do you need this, but this is all you show:
       calResourceScheduling.SelectedView = eCalendarView.Month;
    }
}


在使用控件的代码中:


In the code using the control:

SomeUserControl : myControlInstance = //...
Button myButton = //...

//...

myButton.Click += (sender, eventArgs) => {
   myControlInstance.SomeNewMethod();
}



[END EDIT]

就这么简单.

我在对问题的评论中描述了相反的情况,请参阅.如果您需要更多棘手的案例,请提供反馈并提出一些后续问题.

—SA



[END EDIT]

As simple as that.

I described the opposite situation in my comment to the question, please see. If you need some more tricky cases, please provide your feed back and ask some follow-up questions.

—SA


在这里,我创建了一个具有button1的UserControl.
当您按下按钮时,只需检查TextFeild是否不为null即可将button1的事件传递给父窗体.然后,父窗体处理该事件并显示一个POPUP.
触发了用户控件的SubmitClicked事件,该事件在父表单中处理.
显示流行音乐..

Here i created a UserControl having a button1
when you press button it simply check the TextFeild if it is not null the Event of button1 is passed to the parent form. Then Parent form handle the Event and shows a POPUP.
the event SubmitClicked of usercontrol fired which is handled in Parent Form.
Which shows pop..

public partial class UserControl1 : UserControl
   {
       public UserControl1()
       {
           InitializeComponent();
       }
       public delegate void SubmitClickedHandler();
       // Declare the event, which is associated with our
       // delegate SubmitClickedHandler(). Add some attributes
       // for the Visual C# control property.
       [Category("Action")]
       [Description("Fires when the Submit button is clicked.")]
       public event SubmitClickedHandler SubmitClicked;
       // Add a protected method called OnSubmitClicked().
       // You may use this in child classes instead of adding
       // event handlers.
       protected virtual void OnSubmitClicked()
       {
           // If an event has no subscribers registerd, it will
           // evaluate to null. The test checks that the value is not
           // null, ensuring that there are subsribers before
           // calling the event itself.
           if (SubmitClicked != null)
           {
               SubmitClicked();  // Notify Subscribers
           }
       }
       // Handler for Submit Button. Do some validation before
       // calling the event.
       private void button1_Click(object sender, System.EventArgs e)
       {
           if (txtName.Text.Length == 0)
           {
               MessageBox.Show("Please enter your name." , "Event Handled by UserControl");
           }
           else
           {
               //Notify the parent control
               OnSubmitClicked();
           }
       }

       private void UserControl1_Load(object sender, EventArgs e)
       {

       }


   }
// code for your Form1.cs looks like this.
namespace WindowsFormsApplication3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void userControl11_SubmitClicked()
        {
            MessageBox.Show("Event Handled by Parent Form");
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}

Form1.designer.cs looks like this

 partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.userControl11 = new WindowsFormsApplication3.UserControl1();
            this.SuspendLayout();
            // 
            // userControl11
            // 
            this.userControl11.BackColor = System.Drawing.SystemColors.ButtonShadow;
            this.userControl11.Location = new System.Drawing.Point(75, 69);
            this.userControl11.Name = "userControl11";
            this.userControl11.Size = new System.Drawing.Size(130, 90);
            this.userControl11.TabIndex = 0;
            this.userControl11.SubmitClicked += new WindowsFormsApplication3.UserControl1.SubmitClickedHandler(this.userControl11_SubmitClicked);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(284, 262);
            this.Controls.Add(this.userControl11);
            this.Name = "Form1";
            this.Text = "Form1";
            this.Load += new System.EventHandler(this.Form1_Load);
            this.ResumeLayout(false);

        }

        #endregion

        private UserControl1 userControl11;
    }



或只是访问此链接,我希望它将使用完整的
http://www.akadia.com/services/dotnet_user_controls.html [



or simply visit this link i hope it will be use full
http://www.akadia.com/services/dotnet_user_controls.html[^]


注意:保持该响应不变变成一本小说,我不会考虑可能需要做的事情:如果其他操作会删除面板内的UserControl.

假设:

0.您要在主窗体上使用但不想在UserControl上使用的按钮将被命名为:"btnDay.

1.约束"是每次单击主窗体上的按钮时,必须删除并重新创建UserControl.

2.根据设计,在任何给定时间,窗体上都将只有一个用户控件.

开始于:

0.从主窗体中删除按钮''btnMonth.

1.在主窗体中添加第二个按钮:在您想要从UserControl移至MainForm的按钮的相同位置,将其名称更改为" btnDay,以重新定位.
给它适当的显示文本,例如:将视图设置为月"或任何您想要的内容.

将"btnDay"的可见属性设置为"false".

现在:假设您有一个窗体,该窗体上有一个面板(该窗体内部没有控件),窗体上有两个按钮,其中一个按钮设置为在应用程序启动时不可见:

并且,假设您的UserControl中有一个使用了Public Modifier的方法,从而允许从UserControl外部的父ContainerControl MainForm对其进行访问(执行).

让我们看看这在实践中如何实现:

1. UserControl的胆量现在仅是:
Note: to keep this response from turning into a novel, I am not going to consider what might need to be done: if some other action deletes the UserControl inside the Panel.

Let''s assume:

0. the Button you want on the Main Form ... but do not want on your UserControl ... is to be named: ''btnDay.

1. a "constraint" is that the UserControl must be deleted and re-created each time a Button on the Main Form is clicked.

2. by design, there will be only one of the UserControls on the Form at any given time.

Start by:

0. remove the Button ''btnMonth from the Main Form.

1. add a second button to the Main Form: at same location you wanted the Button that you intended to move from the UserControl to the MainForm, changing its name to ''btnDay, to be re-located to.

Give it appropriate display-text, perhaps something like: "Set View to Month," or whatever you want.

Set ''btnDay''s Visible Property to ''false.

Now: assuming you have a Form, with a Panel (with no Controls inside it initally) on the Form, and two Buttons on the Form, one of which is set to not be visible when the Application starts:

And, assume you have in your UserControl a Method with the Public Modifier used, allowing it to be accessed (for execution) from outside the UserControl, from its parent ContainerControl, the MainForm.

Let''s see how this works out in practice:

1. The UserControl''s guts are now only:
public ucResourceScheduling()
{
    InitializeComponent();
}
//
// this is just for testing to make sure
// we can call a method in the UserControl
// from the a Button on the MainForm
public void DoSomething(DateTime rightNow)
{
    MessageBox.Show("Have a nice day beginning " + rightNow.ToString("F"));
}

2.表单代码的相关部分如下所示:

2. And the relevant section of the Form''s code looks like:

// keep a Form scoped reference for the added UserControl
// so we can use it in the EventHandler for the second
// Button that changes the View
ucResourceScheduling ui;

private void rtbResourceScheduling_Click(object sender, EventArgs e)
{
// clear the Panel's controls
    panelMainMenu.Controls.Clear();

// create a new instance of the UserControl which is assigned to the
// Form scoped variable 'ui: see footnote [1]
    ui = new ucResourceScheduling();

// add the new UserControl instance to the Panel's ControlCollection
    panelMainMenu.Controls.Add(ui);

    // style it however you like
    ui.Dock = DockStyle.Fill;

    // show the Button that: if clicked:
    // will call the Click EVentHandler
    // which will execute the Public Method
    // 'DoSomething in the new UserControl
    // inside 'panelMainMenu on 'frmMainMenu
    btn_Day.Visible = true;

    // show the new UserControl
    ui.Show();
}

void btn_Day_Click(object sender, EventArgs e)
{
    // if you want to pass parameters to a Public Method
    // inside the UserControl, just define them here
    // and change the DoSomeThing Public Method
    // in the UserControl so it has a matching
    // parameter list, as in this trivial test:
    ui.DoSomething(DateTime.Now); 
}

我很好奇为什么/最终如何在UserControl中使用该按钮,并且首先需要将其重新定位到MainForm.

如果出于某些特殊原因执行该代码以更改View inside 内部的UserControl的范围(因为它实现了Interface?...或?),这是可以理解的.

[1]最好有一个类型为UserControl的Public属性,它具有在UserControl的Load EventHandler中设置的私有" set和只读public" get功能,然后:仅可以通过该Public属性从它共享的同一NameSpace中的任何位置访问UserControl的实例,但是我用光了时间在这里给代码做最后的抛光".

Bill,祝你好运

I am curious about why/how you ended up with that button inside the UserControl, and needing to relocate it to the MainForm in the first place.

If there''s some special reason for executing that code that changes the View inside the UserControl''s scope (because it implements an Interface ? ... or ?), that''s understandable.

[1] it is probably better practice to have a Public Property of Type UserControl, with "private ''set," and "readonly public ''get," functions that is set in the UserControl''s Load EventHandler: and then to access the instance of the UserControl, from anywhere in the same NameSpace it shares, only through that Public Property, but I just ran out of time to give the code here a final "polishing."

good luck, Bill


这篇关于通过表单从用户控件访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆