我如何 order/set 从字典中检查 checkedListBox 控件的状态

how can i order/set check state on a checkedListBox control from a dictionary

我有一个 Dictionary<string, ValuePair>,其中包含有关我的 checkedlistbox 控件的先前状态的信息。我想尝试遍历该词典并调整我当前的检查列表框以反映这一点。 Dictionary 中包含的信息是一个 Name as string,它与列表框中的项目匹配,因此我可以使用它来调用 FindStringExact(),然后 ValuePair class 包含一个 bool 值,表示该项目是否被选中和一个整数,它是该项目先前在列表中的位置的索引值。

如何根据该信息重新设置我的选中列表框?我需要指出的是,我的列表框通过 DataSource 属性 绑定到 inputData.Cameras 自定义 class 对象列表。这是我尝试设置有效的检查状态,但我无法思考如何设置顺序,因为为此我需要编辑控件绑定到的源列表:

foreach (KeyValuePair<string, ValuePair> item in presets.JumpCameras)
{
    int index1 = lbCameras.FindStringExact(item.Key);
    if (index1 != -1)
    {
        UnifyCamera camera = lbCameras.Items[index1] as UnifyCamera;
        lbCameras.SetItemCheckState(index1, item.Value.Value1 == true ? CheckState.Checked : CheckState.Unchecked);
    }
}

我的价值对class:

public struct ValuePair
{
    public bool Value1;
    public int Value2;

    public ValuePair(bool x, int y)
    {
        Value1 = x;
        Value2 = y;
    }
}

可以访问 inputData.Cameras 并且会 return 一个 List<UnifyCamera> 其中 UnifyCamera.Name 将 match/or 如果它不存在于当前控制字典中的键值。

所以我采用了一些蛮力方法,将任务分成两个序列。首先,我重新创建了一个源列表顺序并将我的列表框重新绑定到它以进行刷新。然后我为列表中的项目设置所有检查状态。好奇是否有更有效的方法来做到这一点:

// modify source list order
for (int i = 0; i < lbCameras.Items.Count; i++)
{
    UnifyCamera cam = lbCameras.Items[i] as UnifyCamera;
    if (presets.JumpCameras.ContainsKey(cam.Name))
    {
        this.inputData.Cameras.Remove(cam);
        this.inputData.Cameras.Insert(presets.JumpCameras[cam.Name].Index, cam);
    }
}

// re-set the list box bounding to re-set the order.
((ListBox)lbCameras).DataSource = null;
((ListBox)lbCameras).DataSource = this.inputData.Cameras;
((ListBox)lbCameras).DisplayMember = "Name";

// set check boxes
foreach (KeyValuePair<string, ValuePair> item in presets.JumpCameras)
{
    int index1 = lbCameras.FindStringExact(item.Key);
    if (index1 != -1)
    {
        lbCameras.SetItemCheckState(index1, item.Value.Checked == true ? CheckState.Checked : CheckState.Unchecked);
    }
}