c# - 无法使用 MVVM 设计模式用 Sql server 列填充 ComboBox
问题描述
(我尝试阅读类似的线程,但找不到让我弄清楚这一点的线程(大多数不考虑 MVVM)。)
努力使用 MVVM 设计模式用 Sql 服务器表列填充我的 ComboBox。这是我在 ViewModel (TripViewModel.cs) 中的方法:
public void FillComboBoxLicenseHolders() {
try {
DataSet ds = new DataSet();
using (SqlConnection sqlCon = new SqlConnection(ConnectionString.connectionString)) {
SqlDataAdapter sqlDA = new SqlDataAdapter();
sqlDA.SelectCommand = new SqlCommand("select Foretaksnavn from tblLicenseHolder", sqlCon);
sqlDA.Fill(ds);
}
DataTable dt = new DataTable();
dt = ds.Tables[0];
for (int i = 0; i < dt.Rows.Count; i++) {
DataRow dr = dt.NewRow();
dr = dt.Rows[i];
LicenseHolder licenseHolder = new LicenseHolder();
licenseHolder.Foretaksnavn = dr["Foretaksnavn"].ToString();
LicenseHolders.Add(licenseHolder);
}
} catch (Exception ex) {
MessageBox.Show(ex.Message, "Message", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
如果我设置一个断点,我可以看到它确实按预期获得了列的第一行。但 ComboBox 未填充。
这就是我在 XAML 中绑定 ComboBox 的方式:
<ComboBox Name="cbLicenseHolder" Canvas.Left="50" Canvas.Top="204" Width="291"
ItemsSource="{Binding LicenseHolders, Mode=TwoWay}"
Loaded="{s:Action FillComboBoxLicenseHolders}"/>
我的 BindableCollection 是等效于 ObservableCollection 的 Stylets(框架),在 ViewModel 中设置如下:
private BindableCollection<LicenseHolder> _licenseHolders;
public BindableCollection<LicenseHolder> LicenseHolders {
get => _licenseHolders;
set => SetAndNotify(ref this._licenseHodlers, value);
}
它在构造函数中实例化:
LicenseHolders = new BindableCollection<LicenseHolder>();
这让我觉得我在这里做了一些多余的事情......
感谢阅读,希望这里的人能够纠正我的想法。