1

I want to bind a class member of an element I added to a collection to DisplayMemberPath. I bound a ObservableCollection to ComboBox.ItemSource and want to show the property name in the combobox's list which is a member of my class AxisBase.
Here is my code:

private ObservableCollection<AxisBase> axis { get; set; }

axis I use to hold elements of the following class

class AxisBase
{
    ...
    public string name { get; set; }
    ...
}

This is how my xaml looks like

<ComboBox Name="comboBox_AchsenListe" DisplayMemberPath="{Binding ElementName=axis, Path=AxisBase.name}" ItemsSource="{Binding ElementName=_MainWindow, Path=axis}"</ComboBox>  

Does anyone know how to bind name to DisplayMemberPath?

theknut
  • 2,533
  • 5
  • 26
  • 41
  • look at my answer update. I give you an example. – Sergey K Feb 06 '12 at 14:39
  • Thanks alot. I had to change my ObservableCollection to `public` which finally made it work. Just little little things mess the whole code :) Thanks! – theknut Feb 07 '12 at 06:24

1 Answers1

3

change DisplayMemberPath value

 DisplayMemberPath="name" 
 SelectedValuePath="name"

and look at this question

I have created sample application for you here the xaml

<Window x:Class="ComboBoxSample.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <ComboBox 
            ItemsSource="{Binding Path=AxisBases}" 
            DisplayMemberPath="Name" 
            SelectedValuePath="Name" 
        Height="23" HorizontalAlignment="Left" Margin="200,134,0,0" Name="comboBox1" VerticalAlignment="Top" Width="120" />
</Grid>

here is code behind

using System.Collections.ObjectModel;
using System.Windows;

namespace ComboBoxSample
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        AxisBases = new ObservableCollection<AxisBase>
                        {
                            new AxisBase {Name = "Firts"},
                            new AxisBase {Name = "Second"},
                            new AxisBase {Name = "Third"}
                        };
        //Set the data context for use binding
        DataContext = this;
    }

    public ObservableCollection<AxisBase> AxisBases { get; set; }
}

public class AxisBase
{
    public string Name { get; set; }
}

}

It works OK and binding also in combo box appears 3 items.

Community
  • 1
  • 1
Sergey K
  • 4,071
  • 2
  • 23
  • 34
  • 1
    @theknut: [The manual](http://msdn.microsoft.com/en-us/library/ms752347.aspx), have you read it? – H.B. Feb 06 '12 at 13:19
  • I tried but I even fail at setting the metadata. It can never load my class and the designer crashes. – theknut Feb 06 '12 at 14:23