Here’s the problem:
I have a ‘home button’ with a listener
private void Item_Tap(object sender, TappedRoutedEventArgs e)
{
if (this.Frame != null)
{
this.Frame.Navigate(typeof(Home));
}
}
If I built a User Control, using the ‘home button’ inside it, how can I accomplish the same navigation?
** I’m near to the solution**.
This is the user control:
public sealed partial class TopBarControl : UserControl
{
public Frame Frame { get; set; }
public object Parameter { get; set; }
public TopBarControl(Frame frame)
{
this.InitializeComponent();
this.Frame = frame;
var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
var dateAndTime = DateTime.Now;
Date.Text = dateAndTime.Date.ToString("MM/dd/yyyy");
User.Text = localSettings.Values["userName"].ToString();
//SectionTitle.Text = Parameter.ToString();
}
private void GoHome_Tap(object sender, TappedRoutedEventArgs e)
{
if (this.Frame != null)
{
this.Frame.Navigate(typeof(Main_Menu));
}
}
}
on the xaml user control I have:
<Button Grid.Column="0" HorizontalAlignment="Right" BorderThickness="0">
<Image Source="/Assets/home_icon.png" Tapped="GoHome_Tap"/>
</Button>
Page associated to the user control
public WantedVehicles()
{
this.InitializeComponent();
}
private TopBarControl topBarControl;
protected override void OnNavigatedTo(NavigationEventArgs e)
{
Tit.Text = e.Parameter.ToString();
topBarControl.Frame = this.Frame;
topBarControl.Parameter = e.Parameter;
}
protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
{
}
protected override void SaveState(Dictionary<String, Object> pageState)
{
}
But the button doesn’t work yet.
I understand your problem. Here’s a simple way to create a home button that you can add anywhere in your application and it will navigate home. No need to cascade events or anything like that. Just create a custom control. This is different than a user control. This is just sub-classing the button control. Far more clean an approach.
Three easy steps.
Note: My custom control is going to be called HomeButton and my home page class is going to be called HomePage. Other than that, this should all be out-of-the-box for you.
First, define how your button will look:
Second, define your custom control like this:
Third, and finally, add your home button to your app!
Here’s how it looks:
It even works! 🙂 If you want to style the button more, it will be easy to steal the styling of the BackButtonStyle in your /Common/StandardStyles.xaml file. Then you can have the same View States and all. Anyway, this will get you where you want.
So, this is home button that solves the problem you described in your question. It even solves it in a way that is less problematic than the solution you assumed you would get – since manually bubbling events across contexts can cause nightmares.
I hope this helps.