【问题标题】:User control could not add to winform?用户控件无法添加到winform?
【发布时间】:2014-09-09 09:39:52
【问题描述】:

我正在开发 winform 应用程序。作为同一项目的一部分,我的应用程序中有一个用户控件。我在该用户控件的构造函数中编写了以下代码

 public ctrlCurrentLocation()
    {            
        InitializeComponent();
        string NewLine = System.Environment.NewLine;
        string strHeader = string.Concat("<?xml version=\"1.0\"?>", NewLine, "<TrackMap>", NewLine);
        string strLast = strHeader + string.Concat("</TrackMap>", NewLine);
        strXMLPath = AppDomain.CurrentDomain.BaseDirectory + "JavaScript\\TrackMap.xml";
        FileStream fs1 = File.Open(strXMLPath, FileMode.Create);
        StreamWriter writer1 = new StreamWriter(fs1, Encoding.UTF8);
        writer1.Write(strLast);
        writer1.Close();
        fs1.Dispose();
        .......
        .
        .
    }

现在,在构建解决方案后,此用户控件出现在工具箱中。 当我试图在我的 mainForm 中拖动这个用户控件时,它会抛出设计时异常说

可能是什么原因,它在行抛出错误

FileStream fs1 = File.Open(strXMLPath, FileMode.Create);

【问题讨论】:

    标签: c# winforms user-controls


    【解决方案1】:

    AppDomain.CurrentDomain.BaseDirectory 在设计模式下返回C:\Program Files...\IDE。那不是您的 TrackMap.xmlfile 所在的位置。

    您可以向 UserControl 添加一个属性,例如 ctrlCurrentLocation.MapFilePath,该属性可以在设计器中设置。然后用文件的数据刷新 userControl。

    示例:

    private string _mapFilePath = null;
    
    public ctrlCurrentLocation()
    {            
        InitializeComponent();
    }
    
    private void ReloadMap()
    {
        if(_mapFilePath != null && File.Exists(_mapFilePath))
        {
            string NewLine = System.Environment.NewLine;
            string strHeader = string.Concat("<?xml version=\"1.0\"?>", NewLine, "<TrackMap>", NewLine);
            string strLast = strHeader + string.Concat("</TrackMap>", NewLine);
            strXMLPath = AppDomain.CurrentDomain.BaseDirectory + "JavaScript\\TrackMap.xml";
            FileStream fs1 = File.Open(strXMLPath, FileMode.Create);
            StreamWriter writer1 = new StreamWriter(fs1, Encoding.UTF8);
            writer1.Write(strLast);
            writer1.Close();
            fs1.Dispose();
            .......
            .
            .
        }
    }
    
    public string MapFilePath
    {
        get { return _mapFilePath; }
        set
        {
            _mapFilePath = value;
            ReloadMap();
        }
    }
    

    使用地图路径的代码已从构造函数移至其自己的方法。然后,只要 MapFilePath 属性发生更改,就会调用此方法。

    此属性将出现在设计器的“属性”面板中,因为它是 UserControl 类的公共属性。在那里你可以粘贴文件路径,ReloadMap的代码将被执行。

    【讨论】:

    • 如果您将代码放在 UserControl 的构造函数中 - 该代码也将由 Visual Studio 在设计时执行。是你故意的吗?如果不是 - 检查 IsDesignMode 属性并仅在 IsDesignMode == false 时在 InitializeComponent() 之后执行您的代码
    猜你喜欢
    • 2013-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多