0

I would like to design a comboBox in C# WPF VS2013 on win 7 like

https://msdn.microsoft.com/en-us/library/windows/desktop/dn742404%28v=vs.85%29.aspx#guidelines

My xaml code:

  <ComboBox Grid.Row="1" Grid.Column="1" 
             SelectedItem="{Binding MyObject}"
             Margin="5"  ItemsSource="{Binding MyObjList}" 
             DisplayMemberPath="Name"
   />
   // MyObjList is a list of MyObject
   public class MyObject
   {
        int id; 
        string Name;
    }

Although I have initialized MyObjList in C# code behind it, the dropdown comboBox meue is blank.

I have search some related posts

How to show text in combobox when no item selected?

WPF ComboBox bad blank value

But, none of them work for me.

Could anybody point out where I made a mistake ?

Community
  • 1
  • 1
user3448011
  • 1,469
  • 1
  • 17
  • 39
  • 1
    For binding to work, you need properties. Your MyObject only has member variables and they aren't even public. Change it to: public int id {get;set;} and public string Name {get;set;}. You didn't show the code for MyObjList but I'm assuming it has the same issue. – J.H. Mar 01 '16 at 20:41
  • As mentioned, note that member variables are private unless specified. A good practice is to specify `private` even though it is the default. – dytori Mar 02 '16 at 03:19

1 Answers1

0

Answer to your question was already given by J.H in his comments. Let me elaborate a bit.

Mistakes in your code:

  • Members of the class MyObject should be Properties and not fields.
  • Also, the same with members of the ViewModel (I hope you have defined that as fields)

Here is the working solution:

MyObject.cs

public class MyObject
{
    //int id;
    //string Name;

    public int id { get; set; }
    public string Name { get; set; }
}

MyViewModel.cs

public class MyViewModel
{
    public ObservableCollection<MyObject> MyObjList { get; set; }
}

MainWindow.xaml.cs

public MainWindow()
{
    InitializeComponent();
    ObservableCollection<MyObject> objs = new ObservableCollection<MyObject>();
    objs.Add(new MyObject() { id = 1, Name = "Someone1" });
    objs.Add(new MyObject() { id = 2, Name = "Someone2" });
    this.DataContext = new MyViewModel() { MyObjList = objs };
 }

MainWindow.xaml

<ComboBox Grid.Row="1" Grid.Column="1" 
             SelectedItem="{Binding MyObject}"
             Margin="5"  ItemsSource="{Binding MyObjList}" 
             DisplayMemberPath="Name"/>
Community
  • 1
  • 1
Gopichandar
  • 2,742
  • 2
  • 24
  • 54