Thursday, November 06, 2008

WPF ComboBox binding to LINQ to SQL

This is mostly for my own use – I am senile enough to run into this problem again in the future.

Like all controls in WPF, the ComboBox is full of configurability and extensibility. This can get quite hairy quite quickly – and if you set the wrong parameters when you databind to a LINQ to SQL data source, really funky stuff can happen.

So here is something that worked for me:

<ComboBox Grid.Column="1" Grid.Row="1" VerticalAlignment="Center" IsEditable="False"   
          Margin="10,2" 
          ItemsSource="{Binding Path=Produkt.Modeller}"  
          DisplayMemberPath="Modell"  
          SelectedValuePath="Modell"  
          SelectedItem="{Binding Path=ProduktModell}"  
          />
ItemsSource is relatively easy – just point at the collection of options.


DisplayMemberPath is also relatively easy – it just tells WPF what to display in the ComboBox.



But SelectedValuePath and SelectedItem took some experimentation to get right – the above works for me, but with some variation came some pretty strange bugs. Models being renamed and stuff.



So now I know.

No comments: