[C#.NET][Winform] 文化特性 - 多國語言訊息方塊 / UI Culture–Multiple Languages MessageBox
上篇提到用資源檔來建立多語系的應用程式 [C#.NET][Winform] 文化特性 - 多國語言應用程式 / UI Culture - Multiple Languages Application,這次我想把訊息對話視窗也擺在資源檔內
UI規劃如下
分別依序建立好資源檔內的資料
加入以下程式碼
ResourceManager _localResource = null; private ComponentResourceManager _ResourceManager = new ComponentResourceManager(); private void button1_Click(object sender, EventArgs e) { string name = this._localResource.GetString("Name"); string data = this._localResource.GetString("Data"); if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(data)) { MessageBox.Show(string.Format(data, name)); } } private void Form1_Load(object sender, EventArgs e) { this._localResource = new ResourceManager("ResourceTest.Form1",Assembly.GetExecutingAssembly()); this._localResource.IgnoreCase = false; this.comboBox1.Text = _language[0]; this.comboBox1.DataSource = this._language; } public void CreateResourceManager(Control Control, string Language) { CultureInfo info = new System.Globalization.CultureInfo(Language); Thread.CurrentThread.CurrentUICulture = info;//變更文化特性 this._ResourceManager = new ComponentResourceManager(Control.GetType()); this._ResourceManager.ApplyResources(Control, "$this"); this.ApplyForm(Control); } public void ApplyForm(Control control) { foreach (Control ctrl in control.Controls) { this._ResourceManager.ApplyResources(ctrl, ctrl.Name); if (ctrl.HasChildren) { ApplyForm(ctrl); } } } //切換語系 private void comboBox1_TextChanged(object sender, EventArgs e) { comboBox1.TextChanged -= new EventHandler(comboBox1_TextChanged); CreateResourceManager(this, this.comboBox1.Text); comboBox1.TextChanged += new EventHandler(comboBox1_TextChanged); }
執行結果如下
很好,一切都很順利,也成功的將訊息字串擺到資源檔裡
忘了如何存取資源檔的捧油參考上篇 [C#.NET][VB.NET] 如何取得資源檔 (ResourceManager) 的 資料 / 圖片
惡夢來了,當Winform表單裡有異動屬性時,剛剛所設定的訊息字串都會被VS給清掉
沒關係,換個角度思考,我把訊息建在別的資源檔總可以吧,分別建立資源檔Message.en-US.resx及Message.zh-TW.resx,並用資料夾裝起來,以免方案看起來凌亂
再將this._localResource改為正確的路徑即可,如此一來就不用擔心資源檔被VS清掉了
若有謬誤,煩請告知,新手發帖請多包涵
Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET