RobertPorter
RobertPorter

Reputation: 552

Binding ComboBox ItemsSource does not work in WPF

This is kinda strange cause every example I found there says I'm doing things the right way yet I was unable to get my ComboBox binding to work in WPF.

I just created an empty WPF Application.

public List<string> myCollection { get; set; }

    public MainWindow()
    {
        DataContext = this;
        InitializeComponent();
        myCollection = new List<string> {"test1", "test2", "test3", "test4"};
    }

And here is my xaml for this:

<Window x:Class="WpfApplication2.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=myCollection}" Height="23" HorizontalAlignment="Left" Margin="66,56,0,0" Name="comboBox1" VerticalAlignment="Top" Width="319" />
</Grid>

I have tried Binding myCollection, Binding Path=myCollection, I have tried with and without setting DataContext. Nothing seems to be working.

I have run out of ideas and every example I find out there says this is the correct way and it should be working so thanks for any help i advance.

Upvotes: 7

Views: 11416

Answers (4)

AZ_
AZ_

Reputation: 21909

public List<string> myCollection { get; set; }

    public MainWindow()
    {            
        myCollection = new List<string> {"test1", "test2", "test3", "test4"};
        DataContext = this;

        InitializeComponent(); //-- call it at the end
    }

You have to InitializeComponent after assigning data context.

Upvotes: 0

ΩmegaMan
ΩmegaMan

Reputation: 31721

Sajeetheran answer works because the initialize of the XAML objects looks at the current state and binds to what is there at that time but will fail if one changes the property to something else. I would term that a one-time work-around.

I just wanted to make this using bindings

For most WPF scenarios one wants to use the INotifyPropertyChange mechanision to allow for dynamic changes to be handled by the XAML bindings. If one wants to truly use the power of bindings it goes hand in hand with INotifyPropertyChange. Otherwise Dimitri's answer is just as valid as Sajeetharan's.


The binding does not know of the change because the reference of myCollection does not notify the world of a change in status; hence the data doesn't get displayed.

To facilitate such notification the class used to hold the property needs to adhere to INotifyPropertyChanged and the property myCollection needs to send a notify event. (Note in your case its the main window which is technically workable, but in the MVVM paradigm one wants to seperate the view from the dat and a ViewModel class is used to hold the actual data and provide this notificaiton).

 public MainWindow : INotifyPropertyChanged

Then provide the event that will be subscribed to by the binding targets to the item on the DataContext :

 public event PropertyChangedEventHandler PropertyChanged;

Then the mechanism to provide the change event.

/// <summary>
/// Raises the PropertyChanged event.
/// </summary>
/// <param name="propertyName">The name of the property that has changed.</param>
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
    PropertyChangedEventHandler handler = PropertyChanged;
    if (handler != null)
    {
        handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

Then provide the change for the myCollection

private List<string> _myCollection;

public List<string> myCollection
{
    get { return _myCollection; }
    set { _myCollection= value; OnPropertyChanged("myCollection"); }
}

Upvotes: 0

Dimitris Batsougiannis
Dimitris Batsougiannis

Reputation: 759

at the end of your constructor

comboBox1.ItemsSource = myCollection;

Upvotes: 5

Sajeetharan
Sajeetharan

Reputation: 222720

Set the datacontext after InitializeComponent

 InitializeComponent();          
 myCollection = new List<string> { "test1", "test2", "test3", "test4" };
 DataContext = this;

Upvotes: 7

Related Questions