Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 620
RobertPorter Avatar asked Aug 23 '15 12:08

RobertPorter


2 Answers

Set the datacontext after InitializeComponent

 InitializeComponent();          
 myCollection = new List<string> { "test1", "test2", "test3", "test4" };
 DataContext = this;
like image 51
Sajeetharan Avatar answered Sep 17 '22 22:09

Sajeetharan


at the end of your constructor

comboBox1.ItemsSource = myCollection;
like image 22
Dimitris Batsougiannis Avatar answered Sep 19 '22 22:09

Dimitris Batsougiannis