Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Binding a WPF ComboBox to a List in new Window

I am new to WPF…

I am trying to bind a List to a combobox in a new Window.

The List is in the following class:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public class TestClass
{
    public List<string> ComboBoxItems = new List<string>
    {
        "Item 1", "Item2"
    };
}

From MainWindow a new TestWindow is created:

private void TestWindow_Click(object sender, RoutedEventArgs e)
{
    var test = new TestClass();
        
    var win = new TestWindow { DataContext = test };
    win.Show();
}

In XAML I tried to bind the ComboBoxItems to the ComboBox like:

<Window ...
        Title="TestWindow" Height="200" Width="300">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition />
        </Grid.RowDefinitions>
        <ComboBox Name="combo" ItemsSource="{Binding ComboBoxItems}"/>
    </Grid>
</Window>

I thought when I set the DataContext of this new window to an instance of my TestClass, then I have access to its members (including the list ComboBoxItems) and can bind them.

But the ComboBox is empty:

Empty ComboBox

Can you tell me what I am doing wrong?

By the way:
In XAML Editor there is no IntelliSense?

Visual Studio XAML Editor

Any tips for that?

Thanks!

>Solution :

ComboBoxItems needs to be a property rather than a field to be the source of DataBinding

public List<string> ComboBoxItems { get; } = new List<string>
{
    "Item 1", "Item2"
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading