我有这个数据网格
<DataGrid Grid.Row="3" Name="DataGrid6S" AutoGenerateColumns="False" VerticalScrollBarVisibility="Auto">
<DataGrid.Columns>
<DataGridTextColumn Header="ID" Width="50" Binding="{Binding ID}" Visibility="Collapsed"></DataGridTextColumn>
<DataGridTextColumn Header="Name" Width="200" Binding="{Binding Name}"></DataGridTextColumn>
<DataGridTextColumn Header="Text" Width="200" Binding="{Binding Text}"></DataGridTextColumn>
<DataGridTemplateColumn Header="Edit" Width="*">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Click="Button_Click" >View Details</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
由以下代码填充:
class Test {
public int W { get; set; }
public string X { get; set; }
public string Y { get; set; }
}
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
List<Test> testList = new List<Test>();
testList.Add(new Test() { W = 0, X = "hello", Y = "one" });
testList.Add(new Test() { W = 1, X = "hello", Y = "two" });
testList.Add(new Test() { W = 2, X = "hello", Y = "three" });
testList.Add(new Test() { W = 3, X = "hello", Y = "four" });
var query =
from values in testList
select new { ID = values.W, Name = values.X, Text = values.Y };
DataGrid6S.ItemsSource = query;
}
private void Button_Click(object sender, RoutedEventArgs e) {
var obj = ((FrameworkElement)sender).DataContext;
// Can't access values because it's of an anoymous type.
// What do I have to do to be able to access the values stored here?
}
}
单击按钮时,我想知道单击该按钮的行的ID,但由于行是使用匿名类型初始化的,所以我找不到,我该怎么做才能找出点击行的ID?
注意:这是一个简化版本,假设查询由 5 个连接和一个 where 子句组成。