rig*_*onk 8 c# wpf xaml combobox
我有一个WPF应用程序,其中包含许多组合在一起的组合框.当我切换组合框#1,组合框#2开关等.
这是2个组合框的xaml:
<ComboBox Grid.Row="1" Height="23" HorizontalAlignment="Right" Margin="0,12,286,0" ItemsSource="{Binding}" Name="CboDivision" VerticalAlignment="Top" Width="120" SelectionChanged="CboDivision_SelectionChanged" />
<ComboBox Height="23" HorizontalAlignment="Right" Margin="0,9,32,0" Name="CboCustomerList" ItemsSource="{Binding}" VerticalAlignment="Top" Width="120" SelectionChanged="CboCustomerList_SelectionChanged" Grid.Row="1" />
Run Code Online (Sandbox Code Playgroud)
CboDivision在开始时填充,不需要重置.HEre是调用除法中的更改的代码,它应该触发客户的更改:
private void CboDivision_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
division = CboDivision.SelectedValue.ToString();
CboCustomerList.ItemsSource = null;
BackgroundWorker customerWorker = new BackgroundWorker();
customerWorker.DoWork += new DoWorkEventHandler(FillCustomers);
customerWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(customerWorker_RunWorkerCompleted);
FillCustomers(null, null);
}
Run Code Online (Sandbox Code Playgroud)
当我进行索引更改时,它会调用一个调用以下代码的backgroundworker:
private void FillCustomers(object sender, DoWorkEventArgs e)
{
string connectionString = Settings.Default.ProdConnectionString;
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand SqlCmd = new SqlCommand();
Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;
SqlCmd.CommandType = CommandType.StoredProcedure;
SqlCmd.Parameters.Add("@division", SqlDbType.NVarChar).Value = division;
SqlCmd.Connection = connection;
SqlCmd.CommandText = "sp_GetCustomers";
SqlDataReader reader = null;
connection.Open();
reader = SqlCmd.ExecuteReader();
List<string> result = new List<string>();
while (reader.Read())
{
result.Add(reader["NAME"].ToString());
}
e.Result = result;
}
Run Code Online (Sandbox Code Playgroud)
问题是我无法在CboDivision上切换选择并清除CboCustomerList并将新值重新加载到其中.这是我绑定xaml中的值的方式吗?如何更改CboDivision导致清除CboCustomerList项,然后执行填充例程?
我目前正在重置组合框:
CboCustomerList.SelectedIndex = -1;
Run Code Online (Sandbox Code Playgroud)
但这只是将新的cbocustomerlist查询附加到最后我也试过了
CboCustomerList.Items.Clear()
Run Code Online (Sandbox Code Playgroud)
但是在重新填充框并且用户选择一个项目之后,它只返回一个空引用错误.
好吧,您没有发布所有代码,但一个问题是您没有调用工作线程。
FillCustomers(null, null)用。。。来代替customerWorker.RunWorkerAsync()。
private void CboDivision_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
division = CboDivision.SelectedValue.ToString();
CboCustomerList.ItemsSource = null;
BackgroundWorker customerWorker = new BackgroundWorker();
customerWorker.DoWork += new DoWorkEventHandler(FillCustomers);
customerWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(customerWorker_RunWorkerCompleted);
customerWorker.RunWorkerAsync(); // <-- this
}
Run Code Online (Sandbox Code Playgroud)
让我知道这是否有帮助。如果还有更多问题,请发布其余的代码。