ASP.NET如何通过自定义UserControl更改页面控件?

时间:2010-07-23 08:43:26

标签: asp.net user-controls

我的页面上有一个Label控件和自定义UserControl。我希望,当UserControl中出现某些内容时,它会改变,例如Label的Text属性(正如我所提到的,Label不属于UserControl)。怎么做?

4 个答案:

答案 0 :(得分:2)

UserControl应该是可重用的,所以为了正确地执行此操作,您应该使用Page钩入的UserControl中的事件,即:

public NewTextEventArgs : EventArgs
{
    public NewTextEventArgs(string newText)
    {
        _newText = newText;
    }

    public NewText 
    { 
        get { return _newText; }
    }
}

然后将以下事件添加到UserControl:

public event OnNewText NewText;
public delegate void OnNewText(object sender, NewTextEventArgs e);

然后从用户控件中激活事件:

private void NotifyNewText(string newText)
{
    if (NewText != null)
    {
        NewText(this, new NewTextEventArgs(newText));
    }
}

然后只在页面上使用该事件,而UserControl和Page不再紧密耦合:

然后处理事件并将文本设置为您的标签:

protected void YourControl1_NewText(object sender, NewTextEventArgs e)
{
    Label1.Text = e.NewText;
}

答案 1 :(得分:2)

您最好的选择是使用某种事件来通知包含页面UserControl已更新。

public class MyControl : UserControl {
    public event EventHandler SomethingHappened;

    private void SomeFunc() {
        if(x == y) {
            //....

            if(SomethingHappened != null)
                SomethingHappened(this, EventArgs.Empty);
        }
    }
}

public class MyPage : Page {

    protected void Page_Init(object sender, EventArgs e) {
        myUserControl.SomethingHappened += myUserControl_SomethingHappened;
    }

    private void myUserControl_SomethingHappened(object sender, EventArgs e) {
        // it's Business Time
    }
}

这只是一个基本的例子,但我个人建议使用设计器界面来指定用户控件的事件处理程序,以便在您的设计器代码隐藏中处理赋值,而不是您正在使用的那个。

答案 2 :(得分:1)

您可以通过从自定义UserControl中引发事件来指出这一点。然后页面可以拦截事件并相应地修改标签的Text属性:

http://asp.net-tutorials.com/user-controls/events/

答案 3 :(得分:0)

您可以使用Page属性访问UserControl的页面包含。尝试:

((Page1)this.Page)。Label1.Text =“Label1 Text”;