Reputation: 359
I'm working on a Windows 10 UWP app and I'm using a blank template from the Template10 library. I'm able to get the hamburger menu working without any problems. The app requires a user to log in first and then proceed to the "home page" of the app. I'd like to show the user id of the user at the bottom of the hamburger menu as a secondary button after they log in or show a login option if they're not logged in (or logged out).
Here's the XAML for the secondary button that's supposed to show the user id:
<controls:HamburgerButtonInfo>
<StackPanel Orientation="Horizontal" VerticalAlignment="Center">
<SymbolIcon Symbol="Contact" Width="48" Height="48" />
<TextBlock Name="Username" Margin="12, 0, 0, 0" VerticalAlignment="Center"/>
</StackPanel>
</controls:HamburgerButtonInfo>
The code-behind is simply the default constructor for enabling the hamburger menu shell with code added to display the username.
public Shell(NavigationService navigationService)
{
this.InitializeComponent();
Menu.NavigationService = navigationService;
if(user logged in)
{
Username.Text = Username;
}
else
{
Username.Text = "login";
}
}
The code works partially in that it shows "login" even after the user has logged in. The username is shown only if the app suspends/resumes or exits/restarts. How do I ensure that as soon as the user logs in, the secondary button in the hamburger menu shell gets updated without having to restart/resume the app?
Upvotes: 2
Views: 686
Reputation: 5302
Since you are using Template10, I suggest you to take a look at Model View View Model pattern (Channel9 introductive video).
With this pattern you can remove your code behind section and, from a XAML level, you can do something this:
<TextBlock Name="Username" Text="{Binding UserDataContext.LoginString}" Margin="12, 0, 0, 0" VerticalAlignment="Center"/>
UserDataContext
is a reference to a ViewModel class that exposes some properties, like LoginString
, that can be something like this:
public string LoginString
{
get
{
return _loginString;
}
set
{
if (_loginString == value)
{
return;
}
_loginString = value;
RaisePropertyChanged(() => LoginString);
}
}
Each time from your code you will change the value of _loginString by its property, your TextBlock will be informed and its Text will be updated. In this way, you don't have to change the HamburgerButtonInfo Text in Shell constructor, but anywhere inside your UserDataContext.
Note that RaisePropertyChanged
is from MVVM Light Toolkit.
Upvotes: 2