I have this datagrid
<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>
which is populated by the following code:
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?
}
}
When a button is clicked, I’d like to know the ID of the row on which that button was clicked, but I can’t find out because the rows are initialized with anonymous types, what do I have to do to find out the ID of the clicked row?
note: This is a simplified version assume that query consists of 5 joins & a where clause.
Just create a named type and select instances of that, anonymous types are for objects that are only edited within the scope in which they are created. Also why not use the
Testclass directly? The only difference are property names. Also do not forget to cast theDataContextto your named type as it is anobject.