2011-12-01 55 views
0

我有我的wpf数据网格中Wpf工具包的自动完成框。下面是我的xaml:动态设置wpf工具包Autocompletebox Itemsource

    <DataGridTemplateColumn Header="Account Type"> 
         <DataGridTemplateColumn.CellTemplate> 
          <DataTemplate> 
           <toolkit:AutoCompleteBox Text="{Binding Path='Account Type'}" Populating="PopulateAccountTypesACB" IsTextCompletionEnabled="True" /> 
          </DataTemplate> 
         </DataGridTemplateColumn.CellTemplate> 
        </DataGridTemplateColumn> 

在我的填充事件中,我想根据我正在运行的查询设置itemsource。以下是我目前为此所做的工作:

private void PopulateAccountTypesACB(object sender, PopulatingEventArgs e) 
    { 
     try 
     { 
      List<string> types = new List<string>(); 

      string accountQuery = "SELECT AccountType FROM AccountType WHERE AccountType LIKE '" + e.Parameter +"%'"; 

      SqlDataReader accountTypes = null; 
      SqlCommand query = new SqlCommand(accountQuery, dbConnection); 

      accountTypes = query.ExecuteReader(); 

      while (accountTypes.Read()) 
      { 
       types.Add(accountTypes["AccountType"].ToString()); 
      } 


      accountTypes.Close(); 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message); 

      // Close the DB if there was an error. 
      if (dbConnection.State == ConnectionState.Open) 
       dbConnection.Close(); 
     } 
    } 

如何在此功能中设置ItemSource?我试着给autocompletebox分配一个名称并使用它,但是我无法从那里访问它。

回答

1

我不是舒尔认为这是一个好主意 - 给事件处理函数中执行搜索查询,而是设置ItemSource有只投发件人AutoCompleteBox

AutoCompleteBox accountType = (AutoCompleteBox)sender; 
accountType.ItemSource = types; 
+0

这是为我工作!在事件处理程序中执行查询有什么缺点? –