Mohit
Mohit

Reputation: 113

How to get "Name" property of selected list box item in UWP app

I'm creating a nav menu bar using splitview control in my UWP App. I've created a list box control and added names to each listbox item and want to get name of that particular item when clicked. Here is my XAML code

<ListBox Name="fdMenuOption" SelectionMode="Single" SelectionChanged="fdMenuOption_SelectionChanged"  Background="#37474F">
    <ListBoxItem Name="Products">
        <StackPanel Orientation="Horizontal" Padding="10" VerticalAlignment="Center">
            <TextBlock FontFamily="Segoe MDL2 Assets" 
                                Text="&#xF0E3;"
                                Foreground="White"   
                                FontWeight="Bold"
                                FontSize="28"   />
            <TextBlock Text="Products" 
                                   Foreground="White" 
                                   Margin="20,0,0,0"
                                  />
        </StackPanel>
    </ListBoxItem>
    <ListBoxItem Name="Favorites">
        <StackPanel Orientation="Horizontal" Padding="10" VerticalAlignment="Center">
            <TextBlock FontFamily="Segoe MDL2 Assets" 
                                Text="&#xE728;" 
                                Foreground="White"
                                FontWeight="Bold" 
                                FontSize="28"   />
            <TextBlock Text="Favorites" 
                                   Foreground="White" 
                                   Margin="20,0,0,0"
                                  />
        </StackPanel>
    </ListBoxItem>
    <ListBoxItem Name="Categories">
        <StackPanel Orientation="Horizontal" Padding="10" VerticalAlignment="Center">
            <TextBlock FontFamily="Segoe MDL2 Assets" 
                                Text="&#xE81E;" 
                                Foreground="White"
                                FontWeight="Bold" 
                                FontSize="28"/>
            <TextBlock Text="Categories" 
                                   Foreground="White" 
                                   Margin="20,0,0,0"
                                   />
        </StackPanel>
    </ListBoxItem>
</ListBox>

I'll load a new page on the basis of name of click list box. I've managed to do that by getting the index of selected item but need to chagne the name of page dynamically based on name so will need that as well. Thanks in advance

Upvotes: 0

Views: 350

Answers (1)

VDWWD
VDWWD

Reputation: 35514

You can get the name by casting the sender to the ListBox and the SelectedItem property to a ListBoxItem.

private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    var lb = (ListBox)sender;
    var li = (ListBoxItem)lb.SelectedItem;

    string name = li.Name;
}

Upvotes: 1

Related Questions