Search code examples
wpfmvvmdata-bindingitemscontrolitemssource

WPF Combobox isn't visible in View while using MVVM pattern


I create a wpf project using MVVM patern. In View, when I start a project, I haven't seen any items in ComboBoxes and Labels, though I see items in DataContext in ObservableCollection, when debugging. What could be wrong with Binding in my code?

My XAML code:

<ItemsControl ItemsSource="{Binding Items}" >
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*"  />
                        <ColumnDefinition Width="*"  />
                    </Grid.ColumnDefinitions>
                    <Label  Content="{Binding Name}" Grid.Column="0" Height="26" Width="105" Margin="5,5,0.2,0"/>
                    <ComboBox  ItemsSource="{Binding ComboBoxItems}" Grid.Column="1" />
                </Grid>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

XAML.cs code:

this.DataContext = new ViewModel();
InitializeComponent(); 

ViewModel.cs code:

public ObservableCollection<Model> Items;
public ViewModel()
    {
        Items = new ObservableCollection<Model>();
        Items.Add(new Model { Name = "111111" });
        Items.Add(new Model { Name = "222222" });
        Items.Add(new Model { Name = "444444" });
        Items.Add(new Model { Name = "333333" });
    }

Model code:

    public class Model : INotifyPropertyChanged
        {
    public ObservableCollection<string> ComboBoxItems;

    public Model()
            {
                   ComboBoxItems =new ObservableCollection<string>();
                   ComboBoxItems.Add("111111");
                   ComboBoxItems.Add("222222");
                   ComboBoxItems.Add("444444");
                   ComboBoxItems.Add("333333");
            }
private string _name;
    public string Name
            {
                get { return _name; }
               set
               {
                  _name= value;
                  OnPropertyChanged("Name");
               }
            }
    public void OnPropertyChanged([CallerMemberName]string prop = "")
            {
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs(prop));
            }
  public event PropertyChangedEventHandler PropertyChanged;
       }

Solution

  • You need properties for binding to work.

    Change your variable

     public ObservableCollection<string> ComboBoxItems;
    

    To a property

     public ObservableCollection<string> ComboBoxItems {get;set;}
    

    Similarly Items

    public ObservableCollection<Model> Items;
    

    To

      public ObservableCollection<Model> Items  {get;set;}
    

    You might want to make these propfull and raise property changed in the setter.

    But properties have getter and setters.

    Variables do not, and will not bind.