因?yàn)樽罱龅捻?xiàng)目中,我要通過(guò)XML動(dòng)態(tài)生成窗體,看了UI圖樣,我有些叫苦:我通過(guò)XML動(dòng)態(tài)生成窗體,可是主窗體中UI要用圖標(biāo)來(lái)確定要使用的窗體,怎么才能使主窗體的圖標(biāo)也是動(dòng)態(tài)加載而且圖標(biāo)和要生成的窗體還有關(guān)聯(lián)呢?我又想到用XML,查MSDN,看到只有XmlTextWriter和XmlTextReader里分別有XmlTextWriter.WriteBase64和XmlTextReader.ReadBase64可以操作圖片這種二進(jìn)制字節(jié)的數(shù)據(jù)。但是XmlTextWriter和XmlTextReader遠(yuǎn)不如XmlDocument操作方便,如果用這兩者我就得寫(xiě)太多的代碼。 困擾了我一天,記得以前看到過(guò)一篇文章介紹怎樣將圖片數(shù)據(jù)存儲(chǔ)到Xml文件,可是怎么也找不到,后來(lái)終于在一個(gè)英文網(wǎng)站上找到了相關(guān)內(nèi)容,而且還是2003年貼出來(lái)的,汗。 好了,不廢話了,我把我的實(shí)現(xiàn)代碼貼給大家吧。 private XmlDocument document; private string FilePath = Application.StartupPath + "\\..\\..\\FormStyle.xml"; // FormStyle.xml 文件地址 private void frmMain_Load(object sender, System.EventArgs e) { if(document == null) { document = new XmlDocument(); document.Load(FilePath); } // 只挑選含有Form的節(jié)點(diǎn) XmlNodeList FormNodes = document.GetElementsByTagName("Form"); lbIcons.BeginUpdate(); lbIcons.Items.Clear(); foreach(XmlNode node in FormNodes) { // 把節(jié)點(diǎn)的名稱放到下拉列表里 lbIcons.Items.Add(node.Attributes["Name"].Value); } lbIcons.EndUpdate(); } private void lbIcons_SelectedValueChanged(object sender, System.EventArgs e) { // 查找下拉框所選的窗體下是否有Image元素,若無(wú)則退出 XmlNode node = document.DocumentElement.SelectSingleNode(string.Format("descendant::Form[@Name='{0}']/Image", lbIcons.SelectedItem.ToString())); if(node == null) return; // 如果含有Image元素,就將元素值轉(zhuǎn)換為Base64String,然后放到內(nèi)存流 using (MemoryStream mem = new MemoryStream(Convert.FromBase64String(node.InnerText))) { // 加載內(nèi)存流數(shù)據(jù)為位圖 Bitmap bmp = Bitmap.FromStream(mem) as Bitmap; pictureBox1.Image = bmp; } } private void btnAdd_Click(object sender, System.EventArgs e) { // 如果不存在txtFilePath.Text所指文件,就退出 if(!File.Exists(txtFilePath.Text) || lbIcons.Items.Count == 0) return; if(lbIcons.SelectedIndex == -1) lbIcons.SelectedIndex = 0; if(document == null) { document = new XmlDocument(); document.Load(FilePath); } //Read the bitmap. string data = null; Bitmap bmp = new Bitmap(txtFilePath.Text); using (MemoryStream mem = new MemoryStream()) { bmp.Save(mem, System.Drawing.Imaging.ImageFormat.Bmp); // 將位圖數(shù)據(jù)轉(zhuǎn)換為Base64String放入字符串中 data = Convert.ToBase64String(mem.ToArray()); } // 查找當(dāng)前所選的窗體是否含有Image節(jié)點(diǎn),若就新建一個(gè) XmlNode node = document.DocumentElement.SelectSingleNode(string.Format("descendant::Form[@Name='{0}']", lbIcons.SelectedItem.ToString())); XmlNode ImageNode = document.DocumentElement.SelectSingleNode(string.Format("descendant::Form[@Name='{0}']/Image", lbIcons.SelectedItem.ToString())); if(ImageNode == null) { ImageNode = document.CreateElement("Image"); node.AppendChild(ImageNode); } // 將位圖數(shù)據(jù)保存到XML文檔 ImageNode.InnerText = data; document.Save(FilePath); }
|
溫馨提示:喜歡本站的話,請(qǐng)收藏一下本站!