Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Binding Collection To ComboBox and Selecting an item

I've been knocking my head against this for some time now. I'm not really sure why it isn't working. I'm still pretty new to this whole WPF business.

Here's my XAML for the combobox

<ComboBox 
    SelectedValuePath="Type.FullName"
    SelectedItem="{Binding Path=Type}"
    Name="cmoBox" />

Here's what populates the ComboBox (myAssembly is a class I created with a list of possible types)

cmoBox.ItemsSource = myAssembly.PossibleTypes;

I set the DataContext in a parent element of the ComboBox in the code behind like this:

groupBox.DataContext = listBox.SelectedItem;

I want the binding to select the correct "possible type" from the combo box. It doesn't select anything. I have tried SelectedValue and SelectedItem. When I changed the DisplayMemberPath of the ComboBox to a different property it changed what was displayed so I know it's not completely broken.

Any ideas???

like image 320
Adam Driscoll Avatar asked Nov 22 '08 03:11

Adam Driscoll


1 Answers

You could also set the binding in the xaml rather than in the code-behind (we avoid code behind in our xaml pages wherever possible). I'm assuming that myAssembly is a property on your code-behind for the control and is an instance of your MyAssembly class...

<UserControl 
  x:Class="MyNamespace.MyControl"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  DataContext="{Binding}">

  <ComboBox 
    Width="200" 
    ItemsSource="{Binding Path=myAssembly.PossibleTypes}"
    SelectedValuePath="Type.FullName"  
    SelectedItem="{Binding Path=Type}" 
    Name="cmoBox" />
</UserControl>

It may just be personal preference, but I think it's better practice to have the data bindings in the xaml since it makes it easier to see what each control is bound to without having to rake through the code-behind. Also, if you want to refer to your ComboBox from within code, you should assign an x:Name property to it in the xaml rather than just Name.

like image 74
TabbyCool Avatar answered Nov 10 '22 17:11

TabbyCool