1

如果你有它的类型(即),有没有办法实例化和使用用户控件(.ascx typeof(MyUserControl))?

使用像文本框或下拉列表这样的常规 asp.net 控件,您可以创建一个新实例并将其添加到控件集合中。这似乎不适用于用户控件。虽然您可以创建一个新实例并将其添加到集合中,并触发其所有事件,但它实际上不会呈现到页面。通常,您会Page.LoadControl()使用 .ascx 的路径调用

如果您所拥有的只是它的类型,这就会出现问题。如何获得 .ascx 的路径以提供给该LoadControl方法。理想情况下,我也希望不必引用 Page 对象

4

3 回答 3

3

不,这是不可能的;必须提供ASCX 虚拟路径以动态加载带有标记的用户控件,并且没有虚拟路径类型的内部映射。

但是,因为我仍然很懒惰,所以这是我使用的仍然是“类型安全”的方法,并将解决问题隔离到代码中的单个位置。它仍然需要访问“页面对象”,但会处理一些愚蠢的细节。

以下是简要说明:

  1. 使用该类型查找相对(到我的根)ASCX 路径,使用启发式将类型从命名空间映射到虚拟路径;允许指定手动映射的方法,并在指定时使用它
  2. 将类型的相对路径转为正确/完整的虚拟路径
  3. 使用虚拟路径加载控件
  4. 像什么都没发生一样继续

享受(我只是从我的项目 YMMV 中复制粘贴选择的部分):

    /// <summary>
    /// Load the control with the given type.
    /// </summary>
    public object LoadControl(Type t, Page page)
    {
        try
        {
            // The definition for the resolver is in the next code bit
            var partialPath = resolver.ResolvePartialPath(t);
            var fullPath = ResolvePartialControlPath(partialPath);
            // Now we have the Control loaded from the Virtual Path. Easy.
            return page.LoadControl(fullPath);
        } catch (Exception ex)
        {
            throw new Exception("Control mapping failed", ex);
        }
    }

    /// <summary>
    /// Loads a control by a particular type.
    /// (Strong-typed wrapper for the previous method).
    /// </summary>
    public T LoadControl<T>(Page page) where T : Control
    {
        try
        {
            return (T)LoadControl(typeof (T), page);
        } catch (Exception ex)
        {
            throw new Exception(string.Format(
                "Failed to load control for type: {0}",
                typeof (T).Name), ex);
        }
    }

    /// <summary>
    /// Given a partial control path, return the full (relative to root) control path.
    /// </summary>
    string ResolvePartialControlPath(string partialPath)
    {
        return string.Format("{0}{1}.ascx",
            ControlPathRoot, partialPath);
    }

ControlResolver 的代码清单:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FooBar
{
    class ControlResolver
    {
        const string BaseNamespace = "TheBaseControlNameSpace";

        readonly IDictionary<Type, string> resolvedPaths = new Dictionary<Type, string>();

        /// <summary>
        /// Maps types to partial paths for controls.
        /// 
        /// This is required for Types which are NOT automatically resolveable
        /// by the simple reflection mapping.
        /// </summary>
        static readonly IDictionary<Type, string> MappedPartialPaths = new Dictionary<Type, string>
        {
            { typeof(MyOddType), "Relative/ControlPath" }, // No virtual ~BASE, no .ASXC
        };

        /// <summary>
        /// Given a type, return the partial path to the ASCX.
        /// 
        /// This path is the path UNDER the Control Template root
        /// WITHOUT the ASCX extension.
        /// 
        /// This is required because there is no mapping maintained between the class
        /// and the code-behind path.
        /// 
        /// Does not return null.
        /// </summary>
        public string ResolvePartialPath (Type type)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            string partialPath;
            if (resolvedPaths.TryGetValue(type, out partialPath))
            {
                return partialPath;
            } else
            {
                string mappedPath;
                if (MappedPartialPaths.TryGetValue(type, out mappedPath))
                {
                    resolvedPaths[type] = mappedPath;
                    return mappedPath;
                } else
                {
                    // Since I use well-mapped virtual directory names to namespaces,
                    // this gets around needing to manually specify all the types above.
                    if (!type.FullName.StartsWith(BaseNamespace))
                    {
                        throw new InvalidOperationException("Invalid control type");
                    } else
                    {
                        var reflectionPath = type.FullName
                            .Replace(BaseNamespace, "")
                            .Replace('.', '/');
                        resolvedPaths[type] = reflectionPath;
                        return reflectionPath;
                    }
                }
            }
        }
    }
}
于 2012-09-30T22:57:46.240 回答
0
  ' Load the control 
  Dim myUC as UserControl = LoadControl("ucHeading.ascx") 

  ' Set the Usercontrol Type 
  Dim ucType as Type = myUC.GetType() 

  ' Get access to the property 
  Dim ucPageHeadingProperty as PropertyInfo = ucType.GetProperty("PageHeading") 

  ' Set the property 
  ucPageHeadingProperty.SetValue(myUC,"Access a Usercontrol from Code Behind",Nothing) 

  pnlHeading.Controls.Add ( myUC ) 
于 2019-04-23T08:26:45.003 回答
-1

你可能在这里不走运。

这家伙无法得到帮助。

他们告诉这个人这是不可能的。

于 2011-03-05T18:11:21.027 回答