我刚刚开始我的步骤深入了解wpf mvvm,并且在动态获取带有数据库表的请求文件的路径以便填充组合框之后,很难获得与组合框的良好绑定。 这就是我现在所取得的成就:
public class ComboViewModel: ViewModelBase, INotifyPropertyChanged
{
private TableList tableList1;
private TableList tableList2;
public TableList TableList1
{
get
{
return tableList1;
}
set
{
if (tableList1 != value)
{
tableList1 = value;
OnPropertyChanged("TableList1");
}
}
}
public TableList TableList2
{
get
{
return tableList2;
}
set
{
if (tableList2 != value)
{
tableList2 = value;
OnPropertyChanged("TableList2");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public class TableList
{
public List<string> TBL = null;
public TableList()
{
}
public List<string> TablesList(string mdbDir)
{
DbConnection connection;
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
DataTable userTables = null;
List<string> mdbTblList = new List<string>();
connection = factory.CreateConnection();
connection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + mdbDir;
string[] restrictions = new string[4];
restrictions[3] = "Table";
try
{
connection.Open();
userTables = connection.GetSchema("Tables", restrictions);
for (int i = 0; i < userTables.Rows.Count; i++)
{
mdbTblList.Add(userTables.Rows[i][2].ToString());
}
}
catch
{
}
return mdbTblList;
}
<ComboBox Grid.ColumnSpan="2" Margin="0,40,0,130" DataContext="{Binding ComboViewModel}" SelectedItem="{Binding ListTable1}"> </ComboBox>
&#13;
答案 0 :(得分:1)
让我们专注于视图:为了显示项目绑定ComboBox.ItemsSource
到对象集合(我想是db表名)。该集合应位于组合框'DataContext(ComboViewModel)中。对于组合框中的SelectedItem
绑定,您需要一个与ComboViewModel中集合的泛型类型相同类型的属性ListTable1(为什么不重命名为SelectedTable?)。
修改
public class ComboViewModel : INotifyPropertyChanged {
private List<string> tables;
public List<string> Tables {
get { return tables; }
set {
tables = value;
OnPropertyChanged("Tables");
}
}
private string selectedTable;
public string SelectedTable {
get { return selectedTable; }
set {
selectedTable = value;
// react to user selection
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName) {
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public class FileDialogViewModel {
ComboViewModel ComboVM {
get { /* return ComboViewModel instance */ }
}
void UpdateTables(string mdbDir) {
ComboVM.Tables = TablesList(mdbDir);
}
}
的Xaml
<!-- DataContext has to be the ComboViewModel instance -->
<ComboBox ItemsSource="{Binding Tables}" SelectedItem="{Binding SelectedTable}" />
答案 1 :(得分:0)
我的解决方案是使属性公共ComboViewModel ComboViewModel静态并在activeting filedialogviewmodel上发送表列表