You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将ComboBox的SelectedIndex与连接字符串列表关联实现服务器选择

实现代码调整方案

方案一:通过ComboBoxItem.Tag属性绑定服务器地址(推荐,索引变动也不会出错)

调整后XAML代码

<ComboBox Name="cboxGDAservers" SelectionChanged="cboxGDAservers_SelectionChanged">
    <ComboBoxItem Content="GDA02" Tag="DKCDCVDCP30"/>
    <ComboBoxItem Content="GDA03" Tag="DKCDCVDCP31"/>
    <ComboBoxItem Content="GDA04" Tag="DKCDCVDCP32"/>
</ComboBox>

调整后后台代码

首先修正原方法的已知bug:原方法中return Result写在AddRange之前,会导致逻辑提前终止,数据永远不会被添加到集合中。同时移除原有遍历所有服务器的逻辑,改为接收单个服务器参数执行查询。

// 全局统一维护服务器列表,也可以直接存储在ComboBoxItem的Tag属性中
private readonly string[] GDAServerList = new string[] { "DKCDCVDCP30", "DKCDCVDCP31", "DKCDCVDCP32" };

// ComboBox选中变更事件实现
private void cboxGDAservers_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (cboxGDAservers.SelectedItem is ComboBoxItem selectedItem)
    {
        // 直接从选中项的Tag属性取对应服务器地址
        string targetServer = selectedItem.Tag.ToString();
        // 调用查询方法
        LoadGDAWorkers(targetServer);
    }
}

// 抽离独立的查询加载方法
private async void LoadGDAWorkers(string targetServer)
{
    List<GDAWorkerDataModel> GDAWorkersConsolidated = new List<GDAWorkerDataModel>();
    PbarGDAWorker.IsIndeterminate = true;
    try
    {
        // 调用查询接口,若为异步方法请加await关键字
        var GDAWorkers = GDAAcquisitionViewModel.GetWorkers(targetServer);
        GDAWorkersConsolidated.AddRange(GDAWorkers);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
    finally
    {
        DGGDAWorker.ItemsSource = GDAWorkersConsolidated;
        PbarGDAWorker.IsIndeterminate = false;
    }
}

注意:如果GDAAcquisitionViewModel.GetWorkers是异步实现,需在调用前加await关键字,同时将方法返回值改为Task,避免UI卡顿。

方案二:通过选中索引映射服务器列表(无需修改XAML)

如果不想修改原有XAML代码,直接用选中索引对应服务器数组的下标即可,仅需修改SelectionChanged事件逻辑:

private void cboxGDAservers_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    int selectedIndex = cboxGDAservers.SelectedIndex;
    // 索引有效时才执行查询
    if (selectedIndex >=0 && selectedIndex < GDAServerList.Length)
    {
        string targetServer = GDAServerList[selectedIndex];
        LoadGDAWorkers(targetServer);
    }
}

内容的提问来源于stack exchange,提问作者nhy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 04:54:02