我有一个System.Windows.ListBox
绑定到ObservableCollection<string>
ViewModel 中的 a,ListBox 的 ItemsSource 属性绑定到LbItems
,构造函数包含以下代码:
public DataSetViewModel(DataSetModel _dataSet) {
LbItems.CollectionChanged += lbFiles_CollectionChanged2;
}
考虑以下两种可能的方案选项......
按预期显示(从OpenFileDialog
ListBox 中的相等项中设置的项):
private void lbFiles_CollectionChanged2(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) {
this.DataSet.InputFileSet = LbItems.ToArray();
}
项目显示为未执行(列表框中出现的每个选定项目中的 2 个OpenFileDialog
):
private void lbFiles_CollectionChanged2(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) {
MessageBox.Show("Why does this messagebox cause an binding error?");
}
.
更新
下面是 OpenFileDialog 的代码:
private void btnLoad__Click(object sender, RoutedEventArgs e) {
OpenFileDialog ofd = new OpenFileDialog();
ofd.Multiselect = true;
ofd.Filter = "CSV File (.csv)|*.csv";
ofd.InitialDirectory = @"%userprofile%\Documents";
ofd.Title = "Load CSV data sources";
if (ofd.ShowDialog() == true) {
((DataSetViewModel)this.DataContext).LbItems.Clear(); //bad code - please comment on proper strucutre for MVVM
foreach (string str in ofd.FileNames) {
((DataSetViewModel)this.DataContext).LbItems.Add(str);
}
}
}