【问题标题】:How to set public bool value in C# code behind, read in .ascx User Control?如何在后面的 C# 代码中设置公共布尔值,在 .ascx 用户控件中读取?
【发布时间】:2015-06-15 15:43:34
【问题描述】:

我想稍微修改一个由各种 .aspx 页面加载的用户控件。

如果我在 .aspx.cs 页面中设置布尔值

public bool showTemplateBGOption;

public bool TemplateBGOption
{
    set { showTemplateBGOption = false; }
}

如何读取在同一个 .aspx 页面上呈现的 .ascx 控件中的布尔值 showTemplateBGOption?

【问题讨论】:

  • 为您的TemplateBDOption 属性添加吸气剂?但是为什么你首先要有一个公共领域呢?

标签: c# .net


【解决方案1】:

您可以将 Page 属性转换为正确的类型,页面属性需要一个 getter。

(在你的 ascx 代码隐藏的某个地方):

MyPageType page = this.Page as MyPageType;
if(page != null)
{
    bool templateBGOption = page.TemplateBGOption;
}

但是通过这种方式,您将使用UserControl 硬连接页面。相反,该页面应将TemplateBGOption 指定为UserControl。

(在页面代码隐藏的某个位置):

this.UserControl1.TemplateBGOption = this.TemplateBGOption;

【讨论】:

    【解决方案2】:

    您可以为将使用此属性的所有页面实现一个接口,然后在用户控件中使用它,这样您就可以将用户控件与特定页面分离,但您可以按照“合同”进行操作

    interface ITemplateBOption
    {
     bool TemplateBGOption{get;set;}
    }
    
    Public MyPage : Page,  ITemplateBOption
    {
     public bool TemplateBGOption 
     {
      get{...}
      set{...}
     }
    }
    

    在您的用户控件中使用如下:

    ITemplateBOption page = this.Page as ITemplateBOption;
    if(page != null)
    {
        bool templateBGOption = page.TemplateBGOption;
    }else
    {
    //do something, thrown an exception for example.
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多