1

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.

3 Answers 3

9

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:

<!-- custom home button -->
<Style TargetType="local:HomeButton" BasedOn="{StaticResource BackButtonStyle}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Grid Height="48" Width="48">
                    <Ellipse Stroke="White" StrokeThickness="2" />
                    <TextBlock Text="&#xE10F;" FontSize="20" 
                               VerticalAlignment="Center" HorizontalAlignment="Center" />
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Second, define your custom control like this:

public sealed class HomeButton : Button
{
    public HomeButton()
    {
        this.DefaultStyleKey = this.GetType();
        this.Click += HomeButton_Click;
    }

    void HomeButton_Click(object sender, RoutedEventArgs e)
    {
        var _Frame = Window.Current.Content as Frame;
        var _Type = typeof(HomePage);
        _Frame.Navigate(_Type);
    }
}

Third, and finally, add your home button to your app!

<local:HomeButton HorizontalAlignment="Left" VerticalAlignment="Top" Margin="40" />

Here's how it looks:

enter image description here

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.

2
  • As an aside, it is important to try to use vector images in your buttons instead of PNG or JPG files. This is not because those files do not work. It is because vectors correctly "dim" when they are disabled. Images remain bright "white" and just cause more problems. That is a general principle. Because you are styling your own button from scratch, an enabled and disabled version of your image could be incorporated, too, but why? blog.jerrynixon.com/2012/03/… & timheuer.com/blog/archive/2012/09/03/… Jan 8, 2013 at 21:20
  • I blogged about this answer if you are interested blog.jerrynixon.com/2013/01/… Jan 9, 2013 at 5:41
1

Add a button to your user control, and attach Item_Tap event handler to it.

<UserControl>
  ....
  <Button  Tapped="GoHome_Tap">Go Home</Button>
 .....
</UserControl>

Add Frame to MyUserControl.cs. See your other question to know how to set the Frame property from enclosing Page.

 public TopBarControl:UserControl
 {
    public Frame Frame {get;set;} // To be set in either OnNavigatedTo, or in Constructor. 

 }

Add Event Handler to MyUserControl.cs

private void GoHome_Tap(object sender, TappedRoutedEventArgs e)
{
    if (this.Frame != null)
    {
        this.Frame.Navigate(typeof(Home));
    }
}
8
  • "Add a button to your user control, and attach Item_Tap event handler to it." You mean GoHome_Tap event? By the way I updated the question with the actual situation. Jan 8, 2013 at 19:26
  • You have not set Frame. I have updated the answer. You can accept Frame in the Constructor. can you show the page/window code where you are creating TopBarControl user control.
    – Tilak
    Jan 8, 2013 at 19:30
  • That give me an error "MyUserControl.cs doesn't contain a constructor that accepts 0 arguments ". I updated the question with the code you asked: there is nothing about the user control, I use it in the xaml. Jan 8, 2013 at 19:53
  • In the on navigated to, add the line myUserControl.Frame = this.Frame in WantedVehicles class
    – Tilak
    Jan 8, 2013 at 19:58
  • Maybe we're at the crucial point. I receive this error "Unable to build the type MyUserControl XAML. To be built in XAML, a type can not be abstract, interface, nested, or a generic struct and must have a public default constructor". I've updated again the actual code, in the question. Jan 8, 2013 at 20:07
0

You have to add an event to your UserControl that is fired in the button's event handler. The event that you posted above would still be defined outside of your user control unless you passed whatever "this" was into the UserControl's constructor.

1
  • Say I create 'GoHome_Tap' in UserControl. How can I call the function 'Item_Tap' inside it? Jan 8, 2013 at 17:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.