私はWPFを学んでいますが、問題があります。フォームの読み込み中にコンボボックスのデータを初期化しようとしましたが、何も得られませんでした。これが私のコードです:
xaml:
<Menu x:Name="mn_MainMenu" HorizontalAlignment="Left" Height="35" VerticalAlignment="Top" Width="518">
<ComboBox Name="cbm_Menu" SelectedIndex="0" Width="340">
</ComboBox>
<Button HorizontalAlignment="Right" Content="Demo" Width="50"/>
<Button HorizontalAlignment="Right" Content="Source Code" Width="80"/>
</Menu>
xaml.cs:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
InitCbxData(StaticVariable.ComboBoxData);
}
private void InitCbxData(string[] initStrings)
{
var comboBoxData = new ComboBoxData(initStrings);
this.cbm_Menu.ItemsSource = comboBoxData.Items;
this.cbm_Menu.DisplayMemberPath = "Name";
this.cbm_Menu.SelectedValuePath = "Id";
this.cbm_Menu.SelectedValue = "1";
}
}
これは、デバッグ中のスクリーンショットです。
アップデート:
public class ComboBoxData:ItemCollection
{
public ComboBoxData(params string[] initStrings) : base(initStrings) { }
public ComboBoxData(string initString, char[] delimiters) : base(initString, delimiters) { }
}
public class Item
{
public int Id;
public string Name;
public Item(int id, string name)
{
this.Id = id;
this.Name = name;
}
}
public class ItemCollection : IEnumerable
{
public Item[] Items;
public int Ctr = 0;
public ItemCollection(params string[] initStrings)
{
this.Items = new Item[initStrings.Count()];
foreach (var s in initStrings)
{
this.Items[Ctr] = new Item(Ctr++, s);
}
}
public ItemCollection(string initString, char[] delimiters)
{
string[] stringElements = initString.Split(delimiters);
foreach (var s in stringElements)
{
this.Items[Ctr++] = new Item(Ctr, s);
}
}
public IEnumerator GetEnumerator()
{
return new ItemCollectionEnumerator(this);
}
}
public class ItemCollectionEnumerator : IEnumerator
{
public int position = -1;
public ItemCollection itemCollection;
public ItemCollectionEnumerator(ItemCollection itemCollection)
{
this.itemCollection = itemCollection;
}
public object Current
{
get { return itemCollection.Items[position]; }
}
public bool MoveNext()
{
if (position < itemCollection.Items.Length - 1)
{
position++;
return true;
}
else
{
return false;
}
}
public void Reset()
{
position = -1;
}
}