我有一个与一些数据绑定的网格,来自数据库,如下所示和一个编辑按钮
<DataGrid AutoGenerateColumns="False" Name="SParts_grid" HorizontalAlignment="Center" Margin="32,101,32,0" VerticalAlignment="Top" Height="187" Width="530" >
<DataGrid.Columns>
<DataGridTextColumn Header="Part No" Binding="{Binding Path=SPartID}" />
<DataGridTextColumn Header="Part Code" Width="85" Binding="{Binding Path=SPartCode}" />
<DataGridTextColumn Header="Part Name" Width="160" Binding="{Binding Path=SPartName}" />
<DataGridTextColumn Header="Model" Width="120" Binding="{Binding Path=ModelName}" />
<DataGridTextColumn Header="Location" Binding="{Binding Path=SPartLocation}" />
<DataGridCheckBoxColumn Header="Active" Width="58" Binding="{Binding Path=SPartActive}" />
</DataGrid.Columns>
</DataGrid>
<Button x:Name="btnEdit" Content="Edit" HorizontalAlignment="Left" Margin="105,323,0,0" VerticalAlignment="Top" Width="75" Click="btnEdit_Click"/>
TblSpareParts
从称为一列的db 表中获取的所有数据"ModelName"
都来自另一个名为TblBikeModels
所以我的代码在下面以获取数据
window loaded function
private void Window_Loaded(object sender, RoutedEventArgs e)
{
LoadParts();
}
private void LoadParts()
{
RST_DBDataContext conn = new RST_DBDataContext();
var AllPArts = (from s in conn.TblSpareParts
join m in conn.TblBikeModels on s.ModelID equals m.ModelID
select new { s.SPartName, s.SPartCode, s.SPartLocation, s.SPartID, m.ModelName }).ToArray();
SParts_grid.ItemsSource = AllPArts;
}
它工作得很好,但现在如果我需要选定的项目,它不能按如下方式工作
private void btnEdit_Click(object sender, RoutedEventArgs e)
{
TblSparePart SelectedSPData = SParts_grid.SelectedItem as TblSparePart;
if (SelectedSPData == null)
{
MessageBox.Show("You Must Select a Part");
}
else
{
MessageBox.Show("Selected");
}
}
但是当我使用这个LoadParts
功能然后selecteditem
工作正常但它没有显示ModelName
列中的数据
private void LoadParts()
{
RST_DBDataContext conn = new RST_DBDataContext();
List<TblSparePart> AllPArts = (from s in conn.TblSpareParts
select s).ToList();
SParts_grid.ItemsSource = AllPArts;
}
基本上问题出在LoadParts
功能上