C#WPF组合框项源绑定问题



我在将ComboBox ItemsSource与列表绑定时遇到问题。我从csv文件中读取了工作区。它看不到"工作场所"列表。请告诉我怎么了。xaml:

<ComboBox Grid.Column="1" Grid.Row="9" Height="25" Margin="0,18,0,0" ItemsSource="{Binding Workplaces}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding title}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>

xaml.cs:

public partial class MainWindow : Window
{
private BindableCollection<WorkplaceInfo> Workplaces { get; set; }
public MainWindow()
{
InitializeComponent();
Workplaces = new BindableCollection<WorkplaceInfo>(GetWorkplaces());
}
private List<WorkplaceInfo> GetWorkplaces()
{
List<WorkplaceInfo> workplaces = new List<WorkplaceInfo>();
using (var streamReader = new StreamReader("Workplaces.csv"))
{
using (var csvReader = new CsvReader(streamReader, CultureInfo.InvariantCulture))
{
//csvReader.Context.RegisterClassMap<WorkplaceInfoClassMap>();
var workplaceInfoList = csvReader.GetRecords<dynamic>().ToList();
foreach (var wi in workplaceInfoList)
{
workplaces.Add(new WorkplaceInfo(wi.title, wi.member_of.Split(";")));  
}
}
}
return workplaces;
}
}

WorkplaceInfo类:

class WorkplaceInfo
{
public String title { get; }
public String[] memberOfList { get; }
public WorkplaceInfo(string title, string[] memberOfList)
{
this.title = title;
this.memberOfList = memberOfList;
} 
}

以下是优化后的代码:

public ObservableCollection<WorkplaceInfo> Workplaces { get; set; }
public MainWindow()
{
this.DataContext = this;
Workplaces = new ObservableCollection<WorkplaceInfo>(GetWorkplaces());
InitializeComponent();

}
private List<WorkplaceInfo> GetWorkplaces()
{
List<WorkplaceInfo> workplaces = new List<WorkplaceInfo>();
try
{
using (var streamReader = new StreamReader("Workplaces.csv"))
{
using (var csvReader = new CsvReader(streamReader, CultureInfo.CurrentCulture))
{
//csvReader.Context.RegisterClassMap<WorkplaceInfoClassMap>();
var workplaceInfoList = csvReader.GetRecords<dynamic>().ToList();
foreach (var wi in workplaceInfoList)
{
var titl = wi.title;
workplaces.Add(new WorkplaceInfo(wi.title, new List<string>() { wi.member_of }.ToArray()));
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
return workplaces;
}

因此,代码中需要的更改是:

  1. 将您的Workplaces集合设置为公共ObservableCollection
  2. 添加DataContext绑定
  3. 在初始化主窗口之前读取日期并创建集合(反过来,除非实现INotifyPropertyChanged事件,否则UI不会检测到对象中的更改(

p.s.我不知道你的csv文件的结构,所以我做了一个类似(Workplaces.csv(的小演示,并采用了解析器。如果解析器与csv文件结构匹配,则可以保留它

title;member_of 
London;First 
Amsterdam;Second

我强烈建议在处理文件和处理应用程序外部的任何内容时始终使用try-catch块。

致以最良好的问候。

最新更新