Search code examples
c#xamlbindingwindows-store-appsdatatemplate

Windows store app, How to get the header value of gridview?


Here is the groupstyle of gridview in .xaml.

        <GridView.GroupStyle>
            <GroupStyle>
                <GroupStyle.HeaderTemplate>
                    <DataTemplate>
                        <Button x:Name="HeaderBtn" Click="HeaderButton_Click">
                            <StackPanel Orientation="Horizontal">
                                <TextBlock x:Name="Title" Text="{Binding Key}" />
                                <TextBlock Text="{StaticResource ChevronGlyph}" />
                            </StackPanel>
                        </Button>
                    </DataTemplate>
                </GroupStyle.HeaderTemplate>
             </GourpStyle>
        </GridView.GroupStyle>

The binding value key is the key of list.

Here is the button action.

    private void HeaderButton_Click(object sender, RoutedEventArgs e)
    {

    }

When I click the button, how I get the text value of text block whose x:Name is "Title"?


Solution

  • 2 options :

    The MVVM way would be to use an ICommand instead of the event and pass the value as the command parameter.

    <Button x:Name="HeaderBtn" Command="{Binding HeaderCommand}" CommandParameter="{Binding Title}">
    

    In the event Handler, you should be able to retrieve the data context of the button, and the value of title

    private void HeaderButton_Click(object sender, RoutedEventArgs e)
    {
    var button = (Button)sender;
    var dataContext = (HeaderClass)button.DataContext;
    var title = dataContext.Title; //here is your value
    }