我正在学习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";
}
}
这是我在调试时的一个screeshot:
更新
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;
}
}
答案 0 :(得分:0)
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";
}
我想这永远不会奏效。首先你收到一个字符串数组,因此,de DisplayMemberPath和SelectedValuePath没有“Name”或“Id”。
在我看来,你唯一需要做的就是
this.cbm_Menu.ItemsSource = initstrings;
DisplayMemberPath和selectedValuePath应该用于具有ID和Name作为属性的对象....(适用于您的场景......)
答案 1 :(得分:0)
问题解决了!
只需要在Item类中修改public field to property。我真的不知道为什么,但它确实有效!
修改为:
public class Item
{
public int Id {get;set;}
public string Name {get;set;}
public Item(int id, string name)
{
this.Id = id;
this.Name = name;
}
}