set property of master page from content page and get that property value from another content page in asp.net

前端 未结 7 862
时光取名叫无心
时光取名叫无心 2021-01-03 01:55

I have a master page with one property name event type. Now I want to set this property from a content page and then that property value should be available to another conte

7条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-03 02:03

    If this property is a custom property that you added to your master page, then you'll have to add a MasterType declaration to the page that is incorporating it.

    <%@ MasterType 
        virtualpath="~/Path/To/Your.master" 
    %>
    

    This allows the web site or application to know the specific type of the master page at compile time and allows you to access it as you would any other property in a control.

    Page.Master.MyCustomerProperty = someValue;
    

    Edit: As a side note, in getting this property down to your next control, it would probably be best to create (and raise) a custom event indicating the property has changed. This way a number of controls can subscribe to the event and "self-update" without having to be concerned with the timing of when the property is set.

    Example: In your master page you can define an event as a "global" variable. Then in your property you can raise this event.

    public event EventHandler myPropertyChanged;
    public delegate void MyPropertyChanged(object sender, EventArgs e);
    
    //...
    
    public string MyProperty
    {
        get
        {
           return _myProperty;
        }
        set
        {
            _myProperty = value;
            if (myPropertyChanged != null)
                myPropertyChanged(this, new EventArgs());
        }
    }
    

    Then in your other controls, you can subscribe to this event to know when it changes:

    protected void Page_Load(object sender, EventArgs e) 
    {
        Page.Master.MyPropertyChanged += new EventHandler(MasterPropertyChanged);
    }
    
    protected void MasterPropertyChanged(object sender, EventArgs e) 
        //Rememeber you need the VirtualType in order for this event to be recognized
        SomeLocalValue = Page.Master.MyProperty;
    }
    

    A good step-by-step tutorial of this process can be found on CodeProject. A good c# custom events tutorial can be found on the MSDN.

提交回复
热议问题