Master
Master

Reputation: 2163

Binding not appearing in ComboBox

I'm trying to bind my combobox itemsource to a collection.

public BindableCollection<NaicsCodeDTO> PriNaics { get; set; }
<ComboBox Grid.Row="1" Grid.Column="0" x:Name="PriNaics" ItemsSource="{Binding PriNaics}"/>

The Query

PriNaics = new BindableCollection<NaicsCodeDTO>(
           ctx.NaicsCodes.Where(x => x.Parent == null).Select(x => new NaicsCodeDTO{ Id = x.Id, Name = x.Name }));
OnPropertyChanged("PriNaics");

When I check the combobox, It just shows the (NameSpace).NaicsCodeDTO, not the exact value. What I tried:

<ComboBox Grid.Row="1" Grid.Column="0" x:Name="PriNaics" ItemsSource="{Binding PriNaics.Name}"/>

NaicCodeDTO.cs:

public class NaicsCodeDTO : IDTO
{
    // Primary Key --------------------------------------------------------
    public int Id { get; set; }

    // Fields -------------------------------------------------------------
    public int MinCode { get; set; }
    public int MaxCode { get; set; }
    public string Name { get; set; }
}

I'm just wondering how do I fix the bindings, I think it's something very small and silly...

Upvotes: 0

Views: 34

Answers (1)

Rohit Vats
Rohit Vats

Reputation: 81263

Set DisplayMemberPath to Name property on comboBox:

<ComboBox Grid.Row="1" Grid.Column="0" x:Name="PriNaics"
          ItemsSource="{Binding PriNaics}"
          DisplayMemberPath="Name"/>

By default comboBox call ToString() on bound object which will print full name for your class. Hence you see (NameSpace).NaicsCodeDTO as an output.

With DisplayMemberPath, you explicitly tell comboBox to bind with entire object but display Name property on UI.

Gets or sets a path to a value on the source object to serve as the visual representation of the object.

Upvotes: 3

Related Questions