Luke Litherland Luke Litherland - 2 months ago 16
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()
{
InitializeComponent();

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; }
}
}


My XAML

<Window x:Class="SteamCodes.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:SteamCodes"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ComboBox x:Name="steamCode" ItemsSource="{Binding Source = Codes}" HorizontalAlignment="Left" Height="43" Margin="122,37,0,0" VerticalAlignment="Top" Width="259"/>
</Grid>
</Window>


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.

Thanks,

Answer

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";
Comments