将集合绑定到 ComboBox 和 DataGrid

Bind collection to ComboBox and DataGrid

我有两个来自 CSV 文件和 REST 的集合 API - 设备和应用程序。 "Device" 类型的每个对象都通过 属性 "ApplicationId" 绑定到它的应用程序。我能够在 DataGrid 中显示每个设备,并且我希望允许用户从分配给每个设备的 ComboBox(放置在每一行中)应用程序 select 并将它们发送到 API。我想在 ComboBox "ApplicationName" 中显示,并通过 selection 在 "Device".

中设置 "ApplicationId"
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>

所以,我填充了 DataGrid 和 ComboBox ,但是我在将 "Value" 从 ComboBox 绑定到 DataGrid 行中的 "ApplicationId" 时遇到了问题。另外,我不知道如何在 ComboBox 中仅显示 App 名称(现在是“[Key,Value]”)以及如何将名称添加到 ComboBox 列。如果这很重要,我正在使用 mahhaps.metro。

在您的 DataGridComboBoxColumn 中,您可以提供 SelectedValueBinding 和 SelectedValuePath

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