Kajbo
Kajbo

Reputation: 1158

WPF bind comboBox to List<string>

I'm trying to programmatically generate combo box items. I'm very new to WPF and don't understand where I'm making a mistake.

This is my List<string>:

public class StatusList : List<string>
{
    public StatusList()
    {
        this.Add("aaa");
        this.Add("bbb");
        this.Add("ccc");
        this.Add("ddd");
    }
}

And I'm trying to show these items in

<DataTemplate>
    <ComboBox Height="22" ItemsSource="{StaticResource StatusList}" SelectedItem="{Binding Status}" />
</DataTemplate>

But ItemsSource="{StaticResource StatusList}" is not recognized

Upvotes: 1

Views: 3479

Answers (2)

rahulaga-msft
rahulaga-msft

Reputation: 4164

You need to first set the DataContext property of your MainWindow, which will provide a default source object for any Bindings where a source is not explictly set (by setting either Source, RelativeSource or ElementName).

The object held by the DataContext is typically called a view model.

Your view model should have a public property Statuses which returns a List<string>

Then in XAML you can declare ItemsSource="{Binding Statuses}"

Statuses may also be declared as ObservableCollection<string> in case you want the UI to updated when elements are added or removed.

Upvotes: 4

ASh
ASh

Reputation: 35720

{StaticResource StatusList} - StatusList here is not type name, it is a resource key.

for {StaticResource} to work it should be defined somethere:

<Window.Resources>
   <local:StatusList x:Key="StatusList"/>
</Window.Resources>

local is an alias for namespace where StatusList is declared. local should be declared in xaml using xmlns

Upvotes: 1

Related Questions