views:

13329

answers:

3

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 Width="200" SelectedValuePath="Type.FullName"  SelectedItem="{Binding Path=Type}" Name="cmoBox" >

   </ComboBox>

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???

+6  A: 

In the Xaml, set ItemsSource="{Binding}" and (in the code behind) set the DataContext to myAssembly.PossibleTypes.

Timothy Khouri
Worked great! Thanks
Adam Driscoll
:) I didn't test it... but I've been getting into WPF a lot recently (due to using it at work)... I figured this was either 100% correct, or way off.
Timothy Khouri
+4  A: 

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.

TabbyCool
A: 

I agree: bindings should be in the XAML. I put ... checking .. nothing at all in the code behind, ever. Data sources are all re-usable "resources".

(well, OK, the code-behind constructor calls InitializeComponent()).

Rick O'Shea