使用组合框选择linq查询

时间:2018-03-09 20:39:04

标签: wpf linq combobox

我有一个从数据库表中填充的组合框。当组合框在窗口中显示时,它具有StationName,但它也具有StationId的“隐藏”值。以下是我如何让组合框显示选项:

StationBox.ItemsSource = dc.WasteTrackerStations;

如何访问该StationId属性以在单独的查询中使用它来填充数据网格?这是我的SelectionChanged事件的代码:

private void StationBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {

        var miquery = from mi in dc.WasteTrackerDBs
                      where mi.StationId == [this value needs to be StationId from combobox selection]
                      select new
                      {
                          mi.MenuItem,
                          mi.LeftOver,
                          mi.Par,
                          mi.UoM,
                          mi.StationId
                      };
        EWDataGrid.ItemsSource = miquery;
    }

1 个答案:

答案 0 :(得分:0)

ComboBox具有SelectedItem属性。它将是dc.WasteTrackerStations集合(或null)的元素。将其转换为具体类型,所有属性都可以访问:

private void StationBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    var item = StationBox.SelectedItem as WasteTrackerStation;
    if (item == null) return;
    var selectedStationId = item.StationId;

    var miquery = from mi in dc.WasteTrackerDBs
                  where mi.StationId == selectedStationId
                  select new
                  {
                      mi.MenuItem,
                      mi.LeftOver,
                      mi.Par,
                      mi.UoM,
                      mi.StationId
                  };
    EWDataGrid.ItemsSource = miquery;
}