Search code examples
c#wpfdata-bindingdatagridcomboboxcolumn

How can I set a selection in a DataGridComboBoxColumn?


How can I set a DataGridComboBoxColumn item selection programmatically?
I want to populate my list with data, and the comboboxitem should set the selected item from the list.

But I dont find any way to achieve that.

In this example the selection should be "Forward"

XAML:

<DataGrid ItemsSource="{Binding }" x:Name="dgSFD"  AlternatingRowBackground="BlanchedAlmond" SelectionChanged="dgSFD_SelectionChanged" AutoGenerateColumns="False">
    <DataGrid.Columns>
    <DataGridTextColumn Binding="{Binding Path=sID}" Header="Step ID"/>
    <DataGridComboBoxColumn x:Name="cbServo"  Header="Servo" SelectedItemBinding="{Binding Servo, Mode =TwoWay}" SelectedValuePath="sFunctionName ,Mode=TwoWay"  DisplayMemberPath="sFunctionName"/>
    </DataGrid>

Class

 public class Step
    {
        public string sID { get; set; }
        public Servo serServo { get; set; }
    }
 public class Servo
    {
        public string sFunction { get; set; }
        public string sServo { get; set; }
     }

C#

    public static List<Step> listStep { get; set; }
    public static List<Servo> listServo { get; set; }



    public MainWindow()
    {
        InitializeComponent();
    }




    public void loadList() 
    {
        dgSFD.ItemsSource = listStep;
        cbServo.ItemsSource = listServo;
    }


    public void testfill()
    {
        Servo newServo = new Servo();
        newServo.sFunctionName = "Forward";
        newServo.sServo = "Left";
        listServo.Add(newServo);

        Step newStep = new Step();
        newStep.serServo = newServo;
        newStep.sID = "1";


        listStep.Add(newStep);
    }

Solution

  • Bind the SelectedItemBinding property to the serServo property of the Step object:

    <DataGridComboBoxColumn x:Name="cbServo" Header="Servo" SelectedItemBinding="{Binding serServo, Mode=TwoWay}" DisplayMemberPath="sFunction"/>