0

私がやりたかったのは、コンボボックス内の特定の文字列をselectedindexにすることです。コンボボックスの内容は、ディレクトリ内のファイルのファイル名です。これは編集可能なコンボボックスです。だから私はやった

private void InitComboBoxProfiles()
{
    string appDataPath1 = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    string configPath1 = appDataPath1 + "/LWRF/ReaderProfiles";
    string[] files = Directory.GetFiles(configPath1);
    foreach( string fn in files)
    {
        ComboBoxProfiles.Items.Add(fn);

    }
    int index = -1;
    foreach (ComboBoxItem cmbItem in ComboBoxProfiles.Items) //exception thrown at this line
    {
        index++;
        if (cmbItem.Content.ToString() == "Default.xml")
        {
            ComboBoxProfiles.SelectedIndex = index;
            break;
        }
    }

}

例外:

System.String 型のオブジェクトを System.Windows.Controls.ComboBoxItem にキャストできません

どうすれば目標を達成できますか? ありがとう、サロジ

4

2 に答える 2

1

ComboBox 項目は文字列であるため、 SelectedItemプロパティを目的の文字列に設定するだけです。

ComboBoxProfiles.SelectedItem = "Default.xml";

これにより、SelectedIndexプロパティが自動的に適切な値に設定されSelectedItemSelectedIndex常に同期が維持されることに注意してください。

于 2013-02-16T22:52:42.570 に答える
0

ComboBoxアイテムのタイプはですstring。コードを次のように変更します。

foreach (string cmbItem in ComboBoxProfiles.Items) 
    {
        index++;
        if (cmbItem == "Default.xml")
        {
            ComboBoxProfiles.SelectedIndex = index;
            break;
        }
    }

ループよりも優れています:

ComboBoxProfiles.SelectedIndex = ComboBoxProfiles.Items.IndexOf("Default.xml");
于 2013-02-16T21:55:48.787 に答える