我有一个DataGrid,其中包含从XML绑定填充的数据。
我想知道如何在C#中获取所选行,更具体地说,我想从我的数据集中返回所选行中“ID”的值。
我可以通过以下方式获取整行内容:
var downloadlistselected = downloadList.SelectedValue.ToString();
但是,我只想要第一列的内容。
有人可以帮忙吗?
<Grid.DataContext>
<XmlDataProvider Source="E:\downloader\downloadConfig.xml" XPath="/xservdownload/downloadItem"></XmlDataProvider>
</Grid.DataContext>
<DataGrid x:Name="downloadList" Height="191" VerticalAlignment="Top" ItemsSource="{Binding}" AutoGenerateColumns="False" AlternatingRowBackground="Gainsboro" IsReadOnly="True" SelectionChanged="DownloadListSelectionChanged" DataContext="{Binding}" IsSynchronizedWithCurrentItem="True">
<DataGrid.Columns>
<DataGridTextColumn Header="ID" Binding="{Binding XPath=ID}" Width="50"></DataGridTextColumn>
<DataGridTextColumn Header="Name" Binding="{Binding XPath=Name}" Width="350"></DataGridTextColumn>
<DataGridTextColumn Header="Status" Binding="{Binding XPath=Status}" Width="100"></DataGridTextColumn>
</DataGrid.Columns>
答案 0 :(得分:1)
这些方面应该做的事情:
var item = (XmlNode)downloadList.SelectedItem;
var value = item.SelectSingleNode("ID").InnerText;
关键是所选项目应该是XmlNode
,您可以从中获得所需的任何内容。
答案 1 :(得分:0)
尝试使用此功能,希望它有所帮助。
public static DataGridCell GetCell(DataGrid dataGrid, int row, int column)
{
DataGridRow rowContainer = GetRow(dataGrid, row);
if (rowContainer != null)
{
DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);
// try to get the cell but it may possibly be virtualized
DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
if (cell == null)
{
// now try to bring into view and retreive the cell
dataGrid.ScrollIntoView(rowContainer, dataGrid.Columns[column]);
cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
}
return cell;
}
return null;
}
获得DataGridCell后,您可能还需要通过VisualTreeHelper类获取子视觉效果。