Search code examples
c#wpfcomboboxdatagridmahapps.metro

Bind collection to ComboBox and DataGrid


I have two collections from CSV file and REST API - Devices and Applications. Every object of type "Device" have binding to it's application by property "ApplicationId". I'm able to display every device in DataGrid, and I want to allow user to select from ComboBox(placed in every row) application assigned to every device and send them to API. I want to display in ComboBox "ApplicationName" and by selection set "ApplicationId" in "Device".

public class Device
{
   public string Name { get; set; }
   public string ApplicationId{ get; set; } //set this
   //...
}
public class Application
{
   public string Name { get; set; }
   public string ApplicationId { get; set; }//to this
   //...
}
public class NewDevicesViewModel
{
    public Dictionary<string, string> Applications { get; set; }//Extracted from Application collection
    public ObservableCollection<Device> Devices { get; set; }//Content of DataGrid
}
public MainWindow(string devicesCsv)
{
    InitializeComponent();
    Mock_InitGrid(devicesCsv);
    devices.ItemsSource = NewDevices.Devices;
    appSellection.ItemsSource = NewDevices.Applications;
} 
<DataGrid x:Name="devices" Margin="10,20,10,0"
              AutoGenerateColumns="True"
              Style="{StaticResource AzureDataGrid}">
                <DataGrid.Columns>
                    <DataGridComboBoxColumn x:Name="appSellection">                            
                    </DataGridComboBoxColumn>
                </DataGrid.Columns>
 </DataGrid>

So, I populated DataGrid and ComboBox , but I have problem with bind "Value" from ComboBox to "ApplicationId" in DataGrid row. Also, I don't know how to display in ComboBox only App name(now it is "[Key,Value]") and how to add name to ComboBox column. I am using mahhaps.metro if thats matters.


Solution

  • In your DataGridComboBoxColumn, you can give SelectedValueBinding and SelectedValuePath

    <DataGridComboBoxColumn x:Name="appSellection" SelectedValueBinding="{Binding ApplicationId}" SelectedValuePath="Value" DisplayMemberPath="Key"/>