bifedefrango
bifedefrango

Reputation: 85

How can I add an icon to the NavigationBar in all pages?

So I'm trying to implement an icon in my NavigationBar, so it can be visible in all my pages... I'm using xamarin forms so I want it to be able in both android and IOS... I'm not sure how to do this, but I was trying to add this in my MyCar.xaml

<customControls:BasePage xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:android="clr-namespace:Xamarin.Forms.PlatformConfiguration.AndroidSpecific;assembly=Xamarin.Forms.Core"
    xmlns:views="clr-namespace:OficinaDigitalX.Views"   
    xmlns:customControls="clr-namespace:OficinaDigitalX.ViewModel"
    x:Name="MyCar">
<customControls:BasePage.Content>
    <AbsoluteLayout>



        <StackLayout Padding="10, 0, 10, 0">


            <ListView 
                ItemsSource="{Binding Path=CarList}"
                IsPullToRefreshEnabled="False"
                SelectedItem="{Binding Path=SelectedCar}">
                <ListView.Header>
                    <Label Text="Os Meus Carros" FontSize="Large" />
                </ListView.Header>
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <TextCell Text="{Binding VID}" 
                                  TextColor="Black" 
                                  Detail="{Binding LicensePlate}"/>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </StackLayout>
    </AbsoluteLayout>
</customControls:BasePage.Content>
</customControls:BasePage>  

This is my MyCar.xaml.cs

namespace OficinaDigitalX.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MyCar : ViewModel.BasePage
{

    public MyCar()
    {
        Extensions.LoadFromXaml(this, typeof(MyCar));
        BindingContext = new MyCarViewModel(Navigation);

    }

this is my MyCarViewModel.cs

public class MyCarViewModel : ViewModelBase
{
    public MyCarViewModel()
    {
    }
    public MyCarViewModel(INavigation navigation)
    {
        this.Navigation = navigation;
        this.SelectedCar = null;
        GetClientCars();
    }

    private List<CarInfo> _CarList;

    public List<CarInfo> CarList
    {
        get
        {
            return _CarList;
        }

        set
        {
            _CarList = value;
            OnPropertyChanged("CarList");
        }
    }

    private CarInfo _SelectedCar;

    public CarInfo SelectedCar
    {
        get
        {
            return _SelectedCar;
        }

        set
        {
            _SelectedCar = value;
            OnPropertyChanged("SelectedCar");

            if (_SelectedCar != null)
                ChangeWindow(_SelectedCar);
        }
    }

    public INavigation Navigation { get; set; }

    private void ChangeWindow(CarInfo car)
    {

        Navigation.PushAsync(new Interactions(car));
        this.SelectedCar = null;

    }

    public void GetClientCars()
    {
        string command = "asdasd";
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format(MainPage.server + command));
        request.ContentType = "application/json";
        request.Method = "POST";
        //request.ContentLength = 999999;

        using (var stream = new StreamWriter(request.GetRequestStream()))
        {
            string postData = JsonConvert.SerializeObject(command);

            //stream.Write(postData);
            stream.Flush();
            stream.Close();
        }

        HttpWebResponse response = null;

        try
        {
            response = (HttpWebResponse)request.GetResponse();
            using (var responseString = new StreamReader(response.GetResponseStream()))
            {
                CarList = JsonConvert.DeserializeObject<List<CarInfo>>(responseString.ReadToEnd());
            }
        }
        catch (WebException ex)
        {
            using (StreamReader reader = new StreamReader(ex.Response.GetResponseStream()))
            {

            }
            throw;
        }
    }

}
}

Can anyone help with this?

Upvotes: 1

Views: 225

Answers (2)

FreakyAli
FreakyAli

Reputation: 16409

The correct way of doing this in my Knowledge is extending the content page:

 public class BasePage : ContentPage
 {

    public ICommand CartItemCommand { get; set; }
    public ICommand NotificationPageCommand { get; set; }
    public BasePage() : base()
    {
        CartItemCommand = new Command(async () => await GoCartItemCommand());
        NotificationPageCommand = new Command(GoNotificationPage);

        Init();
    }

    private void Init()
    {
        this.ToolbarItems.Add(new ToolbarItem()
        {
            Icon = "nav_notification_btn",
            Command = NotificationPageCommand,
        });
        this.ToolbarItems.Add(new ToolbarItem()
        {
            Icon = "nav_cart_btn",
            Command = CartItemCommand
        });
    }

    }

}

And once you are done with that just use this BasePage everywhere in Place of ContentPage

In your XAML

<customControls:Basepage xmlns="http://xamarin.com/schemas/2014/forms"
        xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
        xmlns:android="clr-namespace:Xamarin.Forms.PlatformConfiguration.AndroidSpecific;assembly=Xamarin.Forms.Core"
        xmlns:views="clr-namespace:OficinaDigitalX.Views"
        x:Class="OficinaDigitalX.MainPage"    
        xmlns:customControls="Your Control NameSpace"
        x:Name="Main"
        NavigationPage.HasNavigationBar="True">


</customControls:Basepage> 

And in your Xaml.cs file

public partial class MainPage: BasePage

See to it that both partial classes inherit from one base class i.e BasePage or ContentPage as per your need.

And when you do not want to use the NavBar controls just inherit your XAML classes from a Normal ContentPage.

Goodluck revert in case of queries!

Upvotes: 2

Moien Tajik
Moien Tajik

Reputation: 2311

You have two ways to implement this:

1- NavigationPage.TitleView which you can put your icon in that with the Image tag.

2- Using a custom control named NavBarView and use that in your pages inside ControlTemplate attribute. The implementation of NavBarView could be like this :

<?xml version="1.0" encoding="UTF-8" ?>
<ControlTemplate
    x:Class="YourAppName.View.Controls.NavBarView"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="46" />
            <RowDefinition Height="1" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <StackLayout
            Padding="10,5"
            x:DataType="vm:XeposBaseViewModel"
            BackgroundColor="{StaticResource XeposHeaderBackgroundColor}"
            BindingContext="{TemplateBinding BindingContext}"
            Orientation="Horizontal">
            <!--  YOUR NAVBAR CONTENT HERE -->
        </StackLayout>
        <BoxView Grid.Row="1" BackgroundColor="Black" />
        <ContentPresenter Grid.Row="2" />
    </Grid>
</ControlTemplate>

And usage should be like this:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
    x:Class="YourAppName.View.Sell.SomeView"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:controls="clr-namespace:YourAppName.View.Controls;assembly=YourAppName.View"
    ControlTemplate="{StaticResource NavBar}">
    <!--  Your other page data is here  -->
</ContentPage>

NavBar is defined in App.xaml like this, so you can use it with StaticResource:

<controls:NavBarView x:Key="NavBar" />

Upvotes: 1

Related Questions