我是編程新手,需要幫助...我想創建一個帶有組合框專案的系結。但是 DataBinding 并沒有添加新的 DataBind,它會因為回圈而覆寫舊的 DataBind。所以我想如果你在組合框中選擇一個“Profilname”,就會顯示“路徑”。
但到目前為止,由于覆寫,只會顯示最后加載的 .txt 檔案。
現在是我的問題:如何避免在(foreach)回圈中覆寫 DataBind?
有關資訊:有一個檔案夾,其中包含許多 .txt 檔案,這些檔案都稱為:“profile.txt”。該程式用回圈搜索所有檔案,然后用另一個回圈在檔案中搜索一行,其中包含單詞“profile_name”。然后名稱必須顯示在組合框中,路徑必須系結到組合框中的“專案”/“文本”。
我希望這是可以理解的,如果我的代碼令人困惑或寫得不是很強大,我很抱歉,我正在學習......
foreach (string profiletxt in Directory.EnumerateFiles(profiledirectory, "profile.txt", SearchOption.AllDirectories))
{
foreach (string line in System.IO.File.ReadAllLines(profiletxt))
{
if (line.Contains("profile_name"))
{
string remLine = line.Remove(0, 15);
string dLine = remLine.Replace("\"", "");
// dataBinding
var listProfiles = new List<Profile>() {
new Profile() {Path = profiletxt, Name = dLine,},
};
materialComboBox1.DataSource = listProfiles;
materialComboBox1.DisplayMember = "Name";
materialComboBox1.ValueMember = "Path";
}
}
if (materialComboBox1.SelectedIndex == -1)
{
MessageBox.Show("Error, couldn't find Profiles");
}
}
public class Profile
{
public string Path { get; set; }
public string Name { get; set; }
}
uj5u.com熱心網友回復:
ComboBox 使用其包含可用專案的 ItemSource。在您的內部 foreach 回圈中,您為每個組態檔項的查找宣告一個新的組態檔串列:
var listProfiles = new List<Profile>() {
new Profile() {Path = profiletxt, Name = dLine,},
};
materialComboBox1.DataSource = listProfiles;
相反,您可能希望在第一個 foreach 回圈之前創建一個新的 Profile 串列
var listProfiles = new List<Profile>();
并在內部回圈中,將您的新發現添加到串列中
listProfiles.Add(new Profile() {Path = profiletxt, Name = dLine});
然后,在外回圈之后,您只能分配新的 ItemSource 一次。
您的代碼中還有其他 newby 設計缺陷:
應該不需要在 .xaml.cs“代碼隱藏”中設定 DisplayMember 和 ValueMember。相反,它屬于 xaml 代碼本身,因為它們是靜態的。
作為更一般的建議,請考慮不要在您的代碼中執行任何型別的“業務規則內容”或資料保存。相反,您喜歡將 UI(“視圖”)與資料(“模型”)分開,而“視圖模型”將這兩者分開并實作業務規則。有很多關于這個 MVVM 編程模式的好介紹。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/387475.html
上一篇:如何從字典訪問其他方法?
