Luke Litherland Luke Litherland - 1 year ago 128
C# Question

C# - WPF - ComboBox printing the Object Type

i'm trying to learn WPF and on top of that the MVVM style of doing things.

I have a simple practice app in which i would like to display codes in a combo box.

My Code

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace SteamCodes
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
private ObservableCollection<Codes> codes;
public MainWindow()

codes = new ObservableCollection<Codes>()
new Codes() {CodeID = "1", Code="CODETEXT"}
steamCode.ItemsSource = codes.ToString();

public class Codes
public string CodeID { get; set; }
public string Code { get; set; }


<Window x:Class="SteamCodes.MainWindow"
Title="MainWindow" Height="350" Width="525">
<ComboBox x:Name="steamCode" ItemsSource="{Binding Source = Codes}" HorizontalAlignment="Left" Height="43" Margin="122,37,0,0" VerticalAlignment="Top" Width="259"/>

At the moment my Combo box is Pulling through as each option in the ComboBox is a letter from the line 'System.Collections.Objectmodel.ObservableCollection`1[SteamCodes.Codes]'

Everyone of those letters is a different drop down option in the combo box.

Any Ideas where i have gone wrong.


Answer Source

Your ComboBox ItemSource must be a collection of items, not a string:

steamCode.ItemsSource = codes;

You also have to specify which property of your item must be considered as value to be shown in combobox by setting DisplayMemberPath property:

steamCode.DisplayMemberPath = "Code";

To specify which property of bound objects will be used as actual selected value you have to use SelectedValuePath property:

steamCode.SelectedValuePath = "CodeID";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download