Search code examples
c#uwpdatagridwindows-community-toolkit

Microsoft.Toolkit.Uwp.UI.DataGrid - how to get cell value from button click on the cell


Using Microsoft.Graph, I'm populating UWP Tookit DataGrid as follows.

Question: How can I get the value of the selected cell on a click event of a button on the cell?

Code to populate Grid:

using Microsoft.Graph
..........

// Get the events
        IUserEventsCollectionPage events = await graphClient.Me.Events.Request()
            .Select("subject,organizer,start,end")
            .OrderBy("createdDateTime DESC")
            .GetAsync();

MainPage.Xaml with DataGrid:

<Page
        ....>

    <Grid>
        <controls:DataGrid x:Name="EventList" Grid.Row="1" AutoGenerateColumns="False">
            <controls:DataGrid.Columns>
                <controls:DataGridTextColumn Header="Organizer" Width="SizeToCells" Binding="{Binding Organizer.EmailAddress.Name}" FontSize="20" />
                <controls:DataGridTemplateColumn Header="Subject">
                    <controls:DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <HyperlinkButton x:Name="hlBtnFileDownload" Content="{Binding subject}" Click="hlBtnFileDownload_Click"></HyperlinkButton>
                        </DataTemplate>
                    </controls:DataGridTemplateColumn.CellTemplate>
                </controls:DataGridTemplateColumn>
                ..................
                ..................
            </controls:DataGrid.Columns>
        </controls:DataGrid>
    </Grid>
</Page>

Button Click Event:

I though code should be something similar to the following (as I have used it in WPF datagrid). But here I am not clear what should be the ClassName here since IUserEventsCollectionPage used in the above query is an Interface and an online search does not give much info on this interface.

private void hlBtnFileDownload_Click(object sender, RoutedEventArgs e)
{
    ClassName classObj = dataGridName.SelectedItem as ClassName;
    string id = classObj.ID;
}

UPDATE:

To answer a question from user @ Martin Zikmund, the DataGrid ItemsSource is set as follows:

EventList.ItemsSource = events.CurrentPage.ToList();

Furthermore, I tried the following in the above button click event, but when clicking on cell it returns eventitem below as null. Likewise, using Event eventitem = (sender as FrameworkElement).DataContext as Event; also return eventitem as null.

List<Event> eventitem = (sender as FrameworkElement).DataContext as List<Event>;
            string st = eventitem[1].ToString();

Solution

  • The items bound to individual cells are not List<Event> but just Event so the following should work:

    var event = (sender as FrameworkElement).DataContext as Event;