Search code examples
c#silverlight-4.0bindingsilverlight-toolkit

How to bind the SelectedValue property of a ComboBox to a string property?


I have a DataForm control from the Silverlight Toolkit, and in it I have a ComboBox field. The selected value of the combo box should be bound to one of the properties of my IEditable class, so that when for example "H.S." is selected ,the value of my property becomes H.S. However, the binding changes the value of my property to System.Windows.Controls.ComboBoxItem. The result is the same if I use the SelectedItem property instead, as suggested by some other similar questions on stackoverflow. How should I bind the ComboBox's SelectedValue property to my other property? Here is my XAML(the ItemSource is set in the constructor of the page in C# code):

 <toolkit:DataForm  
                    Name="dataForm" 
                    ItemsSource="{Binding}"  
                    AutoGenerateFields="False"
                    Margin="150, 0, 150, 0"
                    CommitButtonContent="Next"
                    CancelButtonContent="Clear"
                    CommandButtonsVisibility="Commit, Cancel">
                    <StackPanel>
                         <toolkit:DataField LabelPosition="Top">
                            <ComboBox SelectedValue="{Binding Degree, Mode=TwoWay}">
                                <ComboBoxItem Content="H.S." />
                                <ComboBoxItem Content="B.S./B.A." />
                                <ComboBoxItem Content="M.S./M.A." />
                                <ComboBoxItem Content="Ph. D." />
                                <ComboBoxItem Content="M.D." />
                            </ComboBox>
                        </toolkit:DataField>
                    </StackPanel>
</toolkit:DataForm>

Thanks in advance.


Solution

  • Check this article out for a good explanation of all the ComboBox control properties: http://johnpapa.net/binding-to-silverlight-combobox-and-using-selectedvalue-selectedvaluepath-and-displaymemberpath

    Try setting the SelectedValuePath property to content e.g:

    <ComboBox SelectedValue="{Binding Degree, Mode=TwoWay}" SelectedValuePath="Content">     
     <ComboBoxItem Content="H.S." />
     <ComboBoxItem Content="B.S./B.A." />
     <ComboBoxItem Content="M.S./M.A." />  
     <ComboBoxItem Content="Ph. D." /> 
     <ComboBoxItem Content="M.D." />
    </ComboBox>