我正在学习 WPF,但我遇到了问题。我尝试在加载表单时初始化组合框数据,但我什么也没得到。这是我的代码:
xml:
<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>
xml.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;
}
}