从 DataGrid 中的单列中选择的值
我有一个 DataGrid,其中的数据是通过 XML 绑定填充的。
我想知道如何在 C# 中获取所选行,更具体地说,我想从数据集中返回所选行的“ID”值。
我可以通过以下方式获取整行内容:
var downloadlistselected = downloadList.SelectedValue.ToString();
但是,我只想要第一列中的内容。
有人可以帮忙吗?
XAML
<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>
I have a DataGrid with data populated from an XML binding.
I want to know how I can obtain the selected row in C#, more specifically I want to return the value of the 'ID' from the selected row from my dataset.
I can get the entire row contents with:
var downloadlistselected = downloadList.SelectedValue.ToString();
However, I only want the contents from the first column.
Can anyone help?
XAML
<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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
沿着这些思路应该做的事情:
关键是所选项目应该是一个
XmlNode
,您可以从中获取所需的任何内容。Something along those lines should do:
Key being that the selected item should be an
XmlNode
from which you can get whatever you need.尝试一下这个功能,希望对你有帮助。
获取 DataGridCell 后,您可能还需要通过 VisualTreeHelper 类获取子视觉对象。
Try with this function, hope it helps.
After you get the DataGridCell, you might also need to get child visual by VisualTreeHelper class.