【问题标题】:Customize events handling of an asp.net user-control depending on the calling form根据调用表单自定义 asp.net 用户控件的事件处理
【发布时间】:2013-08-30 07:44:58
【问题描述】:

我在两种不同的 aspx 表单中使用 asp.net 用户控件。如何根据调用表单自定义用户控件的事件处理?

void ComboboxCountry_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
  {
            if it is form1 that called the User-control => do process 1

            if it is form2 that called the User-control => do process 2
  }

谢谢。

【问题讨论】:

  • 您可以使用(Control)sender.Parent访问呼叫表单
  • 我没有对象 "sender" 的属性 "Parent" 。也许我错过了什么?
  • ((Control)sender).Parent - 我的错误,错过了大括号。
  • 确实如此。我可以检索调用表单 ID 以将表单标识到用户控件中吗? IF ((Control)sender).Parent.ID = "xxxx" ),那么我在哪里可以获得 ID?或者也许我应该使用 ID 以外的其他属性。
  • 您可以通过 .Name 属性访问它

标签: c# asp.net user-controls


【解决方案1】:

尽管这是否是您尝试实现的好设计:您可以向控件添加一个属性,例如

public BehaviourEnum Behaviour { get; set; } // You need to implement the enum

那你可以

void ComboboxCountry_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
{
    if (Behaviour == BehaviourEnum.Behave1) // etc.
}

实现您的控件的页面需要相应地设置 Behaviour-Property。

编辑:如果您的控件需要与父页面交互,我会在父页面上引入一个界面。然后你可以设计这样的东西:

// The page containing this control needs to implement IMasterpage
public IMasterpage Masterpage { get; set; } 

void ComboboxCountry_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
{
    // Propagate the behavour to your parent page
    Masterpage.CallwatheverMethodInYourInterface();
}

目标是将依赖于父页面的行为传播到父页面本身。这样你就可以保持你的控制苗条和独立。

【讨论】:

  • 你认为这是一个糟糕的设计吗?您能否解释一下原因并提出一种更好的方法来重用用户控件,以及自定义事件处理?谢谢
  • 我的意思是,如果控件需要找出他的父级,这是相当糟糕的设计。依赖项应该从外部注入,你不应该让它依赖于外部环境。我在回答中的第一句话虽然具有误导性,但对于我认为它并不坏的财产。另请参阅我编辑的答案。
  • 我不想在用户控件内部调用父表单方法,我只想设置一个条件告诉用​​户控件:如果是表单 1 调用您,请执行一些东西(例如在用户控件中启用一些文本字段),如果是 Form2 调用 => 做其他东西(例如:保持文本字段禁用)。
  • 那么我可能会选择我向您展示的第一个版本:if (Behaviour == BehaviourEnum.Behave1) // Enable certain fields etc.。我不会根据父页面来制作它,它会导致不灵活。
  • @Believer:父窗体定义控件的行为方式:它相应地设置行为属性。控件本身不应该对它所在的形式感兴趣。没有意义?
猜你喜欢
  • 1970-01-01
  • 2013-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-14
  • 2015-02-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多