I’m so sorry to ask about this, but I’m really new in WPF and I searched for hours trying to find out what’s the matter on this problem.
Given following code:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
List<Data> _Buffer = new List<Data>();
for (int i = 0; i < 50; i++)
{
_Buffer.Add(new Data(i, i.ToString()));
}
//Also tried:
//comboBox1.DataContext = _Buffer.ToArray();
comboBox1.ItemsSource = _Buffer.ToArray();
comboBox1.SelectedValuePath = "Val";
comboBox1.DisplayMemberPath = "ValName";
comboBox1.UpdateLayout();
comboBox1.SelectionChanged += new SelectionChangedEventHandler(comboBox1_SelectionChanged);
}
void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
MessageBox.Show(((Data)e.AddedItems[0]).ValName);
}
struct Data
{
public Data(int Val, string ValName)
{
this.Val = Val;
this.ValName = ValName;
}
public readonly int Val;
public readonly string ValName;
}
}
I guess it suppose to be incredibly easy to bind a simple array to a combo, and actually it is, except for a little problem, it does not show anything in the combo’s list.
XAML:
<ComboBox Height="23" HorizontalAlignment="Left" Margin="109,82,0,0" Name="comboBox1" VerticalAlignment="Top" Width="120" ItemsSource="{Binding}" />
How is the right way to do this?
Because
SelectedValuePathandDisplayMemberPathare paths for the item binding you have to makeValandValNamea property: