evilspoons
evilspoons

Reputation: 406

How do I bind an ObservableCollection to a ComboBox?

How do I get even basic binding to work between a ComboBox and an ObservableCollection? I can't get anything but error messages.

VB:

Class MainWindow
    Dim Units As New ObservableCollection(Of String)

    Private Sub Window_Loaded(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
        Units.Clear()
        Units.Add("in")
        Units.Add("mm")
        Units.Add("cm")
    End Sub
End Class

XAML:

<Window x:Class="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 Height="59" HorizontalAlignment="Left" Margin="136,96,0,0" Name="ComboBox1" VerticalAlignment="Top" Width="319"
              ItemsSource="{Binding Units}"/>
</Grid>

No matter what I do, the ComboBox always seems to be empty and there's an error message in the console:

System.Windows.Data Error: 40 : BindingExpression path error: 'Units' property not found on 'object' ''MainWindow' (Name='')'. BindingExpression:Path=Units; DataItem='MainWindow' (Name=''); target element is 'ComboBox' (Name='ComboBox1'); target property is 'ItemsSource' (type 'IEnumerable')

Upvotes: 0

Views: 3925

Answers (1)

McGarnagle
McGarnagle

Reputation: 102793

In the XAML, change to just {Binding}, or equivalently, {Binding Path=.}:

<ComboBox Height="59" HorizontalAlignment="Left" Margin="136,96,0,0" Name="ComboBox1" VerticalAlignment="Top" Width="319" ItemsSource="{Binding}"/>

Set the Data Context explicitly to the object, from code behind, in the *Window_Loaded* event handler:

ComboBox1.DataContext = Units;

Upvotes: 2

Related Questions