Anddev
Anddev

Reputation: 195

Insert button into NavigationViewItem UWP

I want to use NavigationView as tab navigation for my UWP app, as it has appropriate styling and handles overflow well.

Now I want to add a button to each NavigationViewItemon the right of the label. This button should only be visible when the item is selcted.

I have achieved adding the button in the code below, but I can't figure out how to hide the button when the tab is not selected. I have tried binding the button to a bool on my data-model, which I set to true on ItemInvoked, but that didn't work.

<NavigationView x:Name="NavView"
                PaneDisplayMode="Top"
                OverflowLabelMode="NoLabel"
                IsSettingsVisible="False"
                IsBackButtonVisible="Collapsed"
                MenuItemsSource="{x:Bind TabItems}">

                <NavigationView.MenuItemTemplate>
                    <DataTemplate x:DataType="models:TabNavigationItem">
                        <StackPanel Orientation="Horizontal">
                            <TextBlock Text="{x:Bind Text}" VerticalAlignment="Center"></TextBlock>
                            <Viewbox Width="16" Height="16" VerticalAlignment="Center" Margin="2,0,0,0">
                                <Button Background="{StaticResource Transparent}" VerticalAlignment="Center">
                                    <FontIcon FontFamily="Segoe MDL2 Assets" Glyph="&#xE711;"></FontIcon>
                                </Button>
                            </Viewbox>
                        </StackPanel>
                    </DataTemplate>
                </NavigationView.MenuItemTemplate>
</NavigationView>

Picture of NavView

I have looked at Community Toolkit TabView, but as I handle all navigation myself, and just need a row of selectable items, NavigationView was a better fit for me.

Thank you in advance.

Edit: I already tried

<Viewbox Width="16" Height="16" VerticalAlignment="Center" Margin="2,0,0,0" Visibility="{x:Bind Selected, Converter={StaticResource BoolToVisibilityConverter}, Mode="OneWay"}">

And

private void NavView_OnItemInvoked(NavigationView sender, NavigationViewItemInvokedEventArgs args)
{
    if (args.InvokedItem is TabNavigationItem t)
    {
            t.Selected = true;
    }
    Bindings.Update();
}

Upvotes: 1

Views: 613

Answers (2)

Martin Zikmund
Martin Zikmund

Reputation: 39082

Instead of Bindings.Update you should implement INotifyPropertyChanged in your TabNavigationItem class and fire the PropertyChanged event inside the Selected property setter. This way it should notify the UI and properly update the button visibility. Also, don't forget to un-select all the other items as well.

Upvotes: 2

Capt.Pie
Capt.Pie

Reputation: 108

you can hide the button with the Visibility Property. I would create a converter for that task that takes the bool and returns the visible or collapsed value.

Upvotes: 1

Related Questions