即使您不打算走完整的 MVVM 路线,将应用程序的数据与 UI 控件分开仍然是一个好主意。
1] 在 Window 的构造函数中,创建一个 ObservableCollection<string> 并将其设置为 ScriptBox 控件的 ItemsSource。
private ObservableCollection<string> _scriptBoxCollection;
public MyView()
{
_scriptBoxCollection = new ObservableCollection<string>();
ScriptBox.ItemsSource = _scriptBoxCollection ;
}
2] 更改您的 PopulateListBox() 方法以仅返回文件名集合。在Single Responsibility Principle之后,这些方法不应该关心它们生成的数据是如何使用的。
public ReadOnlyCollection<string> GetMatchingFiles(string folder, string fileSpec) { ... }
返回值为ReadOnlyCollection<T>与Microsoft guidelines一致。
3] 更改按钮单击处理程序,使其更新可观察集合。
private void Button_Click_7(object sender, RoutedEventArgs e)
{
_scriptBoxCollectionClear();
foreach(var item in Functions.GetMatchingFiles("./Scripts", "*.txt")
_scriptBoxCollection.Add(item);
Functions.GetMatchingFiles("./Scripts", "*.lua")
_scriptBoxCollection.Add(item);
}
ForEach 结构是必需的,因为标准 ObservableCollection 不支持 AddRange()。
将此添加到 Functions.cs(并弃用 PopulateListBox() 和任何其他将数据直接写入 UI 控件的类似方法)
public static ReadOnlyCollection<string> GetMatchingFiles(string folder, string fileType)
{
var result = new List<string>();
var dinfo = new DirectoryInfo(folder);
var files = dinfo.GetFiles(fileType);
foreach (var file in files)
{
result.Add(file.Name);
}
return result.AsReadOnly();
}