我有一个WPF程序,允许用户编辑SQL数据表,以获取给定零件号的零件详细信息。用户输入部件号,我使用表适配器使用行过滤器将其部件号详细信息显示到数据网格。我希望能够获取ObservableCollection列表并将其绑定到我的数据网格中的某个列(即,具有部件类型列的部件类型的选择列表下拉列表)。这是我的.cs:
public MainWindow()
{
createDropDowns();
context = new RefreshAppContext();
InitializeComponent();
PartTypeComboBox.ItemsSource = partTypesList;
#if DEBUG
#endif
}
public void findButton_Click(object sender, RoutedEventArgs e)
{
var partNumber = inputBox.Text;
// Searches for part number in db.
var foundPart = context.RefreshPartTypes.Where(x => x.PartNumber == partNumber).ToList();
if (!foundPart.Any() == true)
{
MessageBox.Show("Part not found. Please try another number.");
}
else
{
// Adapter used to fill DT with info from DB based on query(ies).
adapter_PT.Fill(table_PT);
DataView dv = table_PT.DefaultView;
dv.RowFilter = "PartNumber='" + partNumber + "'";
// Fills data grid in UI.
dg.DataContext = dv;
PartTypeComboBox.ItemsSource = table_LV.DefaultView;
}
}
public void createDropDowns()
{
// Populate part styles from lookup table.
partTypesList = new ObservableCollection<string>();
adapter_LV.Fill(table_LV);
List<string> temp = table_LV.AsEnumerable().Select(x => x[2].ToString()).ToList();
foreach (var partType in temp)
{
partTypesList.Add(partType);
}
partTypesList.Add(""); // Add a blank option in case user needs to input blank cell.
}
这是我的.xaml:
<DataGrid x:Name="dg" ItemsSource="{Binding}" AutoGenerateColumns="True" AutoGeneratingColumn="m_grid_AutoGeneratingColumn" HorizontalAlignment="Left" Margin="28,-145,-779,0" VerticalAlignment="Top" Height="165" Width="1222" AlternatingRowBackground="LightGray" AlternationCount="2">
<DataGrid.Columns>
<DataGridComboBoxColumn x:Name="PartTypeComboBox"
Header="PartTypeTest"
DisplayMemberPath="Key"
SelectedValuePath="Id"
SelectedValueBinding="{Binding PartType}"/>
</DataGrid.Columns>
</DataGrid>
我可以使用正确的信息列表创建一个新的ComboBox列,但是我无法将该组合框显示(或绑定?)到我的table_PT数据表中填充的PartType列上。方向?谢谢!
答案 0 :(得分:0)
您需要为每个项目添加指定显示字符串属性路径的DisplayMemberPath
。
<DataGridComboBoxColumn x:Name="PartStylesComboBox" DisplayMemberPath="PartType " Header="Test" SelectedValuePath="{Binding partStylesList}" />
答案 1 :(得分:0)
解决:
<DataGrid x:Name="dg" ItemsSource="{Binding}" AutoGenerateColumns="True" AutoGeneratingColumn="event_AutoGeneratingColumn" HorizontalAlignment="Left" Margin="28,-145,-134,0" VerticalAlignment="Top" Height="165" Width="582" AlternatingRowBackground="LightGray" AlternationCount="2">
<DataGrid.Columns>
<DataGridTemplateColumn x:Name="comboCol" Header="PartTypeTest" Width="150">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding partTypesList, RelativeSource={RelativeSource AncestorType=Window}}"
SelectedItem="{Binding PartType, UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>