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???
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With