So I have a datagrid where I added a button into. When I click the button in a row I want the data out of, what is in that row, in a messagebox. I have no clue how to do this...
Here is the XAML code for the button: `
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button x:Name="btnAdd" Click="BtnAdd_Click" Height="40" Width="80" Padding="2" HorizontalAlignment="Right" Margin="2">
<materialDesign:PackIcon Kind="AddShoppingCart"/>
</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
I have tried this:
private void BtnAdd_Click(object sender, RoutedEventArgs e)
{
try
{
var row = (DataGridRow)grid1.SelectedItem;
MessageBox.Show(row.ToString());
}
catch (System.Exception E)
{
MessageBox.Show(E.ToString());
}
`
So the result I want is the items in the datagrid (from the row where I clicked the button) in a messagebox.
If I understood your question I believe you should cast grid1.SelectedItem
to the type you are using in your data binding instead of DataGridRow
so it would be like var row = (MyTypeVm)grid1.SelectedItem;
, and in the class representing that type you can override the .ToString()
method to display that data however you like it.
in example: Your type would be something like this
public class MyTypeVm
{
public string MyStringProperty {get;set}
public int MyIntProperty {get;set}
public override string ToString()
{
return MyStringProperty + MyIntProperty.ToString();
}
}