Hyperlinks in Xaml to navigate from one page to another - c#

How can I create Hyperlinks in Xaml to navigate from one page to another page? I don't know actually how to use the hyperlink tags.

You can use RequestNavigate event to add a HyperLink class
Xaml:
<TextBlock>
<Hyperlink NavigateUri="http://www.google.com" RequestNavigate="Hyperlink_RequestNavigate">
Click here
</Hyperlink>
</TextBlock>
Code Behind:
private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
{
Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
e.Handled = true;
}

If you are looking for navigating to another page :
<StackPanel Grid.Row="1"
Margin="120,0,120,60">
<HyperlinkButton Content="Click to go to page 2" Click="HyperlinkButton_Click"/>
</StackPanel>
And handle it like :
private void HyperlinkButton_Click(object sender, RoutedEventArgs e)
{
this.Frame.Navigate(typeof(BasicPage2));
}
And to move to external page : As mentioned by #Brainy

Related

Get TextBlock inside Button

I have a Button with a TextBlock embedded inside. When the Button is clicked, I want to be able to fetch the TextBlock inside it and modify it's members.
Here is how my button is setup:
<Button Click="Select_Click" Style="{StaticResource ButtonStyle}" HorizontalAlignment="Left" Padding="0,20,20,20">
<TextBlock Text="My text" FontSize="20" Style="{StaticResource TextBlockStyle}"/>
</Button>
In my code behind I want to be able to access the embedded TextBlock:
public void Select_Click(object sender, RoutedEventArgs e)
{
// Get the `TextBlock` from `sender` here
}
I've taken a look at the visual tree of the Button but I'm not seeing the TextBlock. I called GetVisualChildren() on the Button but I only see a Grid and no way to get to the Textblock.
The content of the Button is stored in its Content property and in your case, the TextBlock is the content of the Button.
public void Select_Click(object sender, RoutedEventArgs e)
{
Button button = (Button)sender;
TextBlock textBlock = (TextBlock)button.Content;
}
Just do some casting and it's pretty simple
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Establish_handlers();
}
void Establish_handlers()
{
Mybutton.Click += Mybutton_Click;
}
private void Mybutton_Click(object sender, RoutedEventArgs e)
{
Button clicked_button = (Button)sender;
TextBlock desired_text = (TextBlock)clicked_button.Content;
Textbox_Show_Button_Content.Text = desired_text.Text;
}
}
<StackPanel>
<Button x:Name="Mybutton">
<TextBlock>Hello</TextBlock>
</Button>
<TextBox x:Name="Textbox_Show_Button_Content"></TextBox>
</StackPanel>

C# / WPF Unmask password inside the passwordBox

How could I unmasked and masked the password inside the passwordBox whenever I click the checkBox? I'm using C# WPF template.
Here is my .XAML code:
<PasswordBox x:Name="passwordBox_password" Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="2" Margin="5" Height="25" />
<CheckBox x:Name="checkBox_showPassword" Grid.Row="3" Grid.Column="1" Margin="5,0,5,5" Content="show password" Checked="checkBox_showPassword_Checked" Unchecked="checkBox_showPassword_Unchecked" />
Here is my .CS code:
private void checkBox_showPassword_Checked(object sender, RoutedEventArgs e)
{
// what to do here ?
}
private void checkBox_showPassword_Unchecked(object sender, RoutedEventArgs e)
{
// what to do here ?
}
Or is there another way to do it in WPF?
It's very simple to do that.
First you should to add the value PasswordChar in your PasswordBox:
<PasswordBox Name="PasswordHidden" PasswordChar="•"/>
Next under the PasswordBox tag you should to add a TextBox with Visibility value setted to Hidden:
<TextBox Name="PasswordUnmask" Visibility="Hidden"/>
And a trigger to show / hide the password, for example a simple text or a button. In my case I'm using a simple text.
<TextBlock Name="ShowPassword"/>
Next you need to add 3 different events in the trigger element, for example (this is valid for TextBlock or Image, if you want to use a Button you should to choose another events):
<TextBlock x:Name="ShowPassword" Text="SHOW" PreviewMouseDown="ShowPassword_PreviewMouseDown" PreviewMouseUp="ShowPassword_PreviewMouseUp" MouseLeave="ShowPassword_MouseLeave"/>
The events are PreviewMouseDown PreviewMouseUp and MouseLeave but you can choose the appropriate event for your situation.
Now in your code you need to program the functions:
private void ShowPassword_PreviewMouseDown(object sender, MouseButtonEventArgs e) => ShowPasswordFunction();
private void ShowPassword_PreviewMouseUp(object sender, MouseButtonEventArgs e) => HidePasswordFunction();
private void ShowPassword_MouseLeave(object sender, MouseEventArgs e) => HidePasswordFunction();
private void ShowPasswordFunction()
{
ShowPassword.Text = "HIDE";
PasswordUnmask.Visibility = Visibility.Visible;
PasswordHidden.Visibility = Visibility.Hidden;
PasswordUnmask.Text = PasswordHidden.Password;
}
private void HidePasswordFunction()
{
ShowPassword.Text = "SHOW";
PasswordUnmask.Visibility = Visibility.Hidden;
PasswordHidden.Visibility = Visibility.Visible;
}
The following link will bring you to the answer you are looking for my good sir. Mr Lamas did a great job of answering the how-to so I'd rather redirect you to the answer :)
showing password characters on some event for passwordbox
I recommend Using MahApps.Metro ... after installing it from nuget.org ... you must use it in the head of your xaml like this
xmlns:controls="http://metro.mahapps.com/winf/xaml/controls"
and then ... just use it's style for your PasswordBox control
<PasswordBox Style="{StaticResource MetroButtonRevealedPasswordBox}" />
you can even change the content for the show icon using the controls:PasswordBoxHelper.RevealButtonContent attached property

NavigationService.Navigate error

I'm quite new on C# programming and I have a problem on my code.
I have created a button and applied on it an event click which open an other page of my project by the technology NavigationService.
This is the script:
private void click_login(object sender, RoutedEventArgs e)
{
NavigationService nav = NavigationService.GetNavigationService(this);
nav.Navigate(new Uri("Window1.xaml", UriKind.RelativeOrAbsolute));
}
When I execute, I get this error:
The object reference is not set to an instance of an object with an InnerException null.
Can you help me please?
Your nav object is null, because you're trying to get the NavigationService for a WPF Window.
But for Navigation you need a Page (Navigation Overview on MSDN)
A Little Working example:
Create to Page's Page1.xaml, Page2.xaml
In the App.xaml change the
StartupUri to StartupUri="Page1.xaml"
Page1 Xaml:
<StackPanel>
<TextBlock Text="Hello from Page1" />
<Button Click="Button_Click" Content="Navigate to page 2"></Button>
</StackPanel>
Page1 cs:
private void Button_Click(object sender, RoutedEventArgs e)
{
NavigationService nav = NavigationService.GetNavigationService(this);
nav.Navigate(new Uri("Page2.xaml", UriKind.RelativeOrAbsolute));
}
Page2 Xaml:
<StackPanel>
<TextBlock Text="Hello from Page2" />
<Button Click="Button_Click" Content="Navigate to page 1"></Button>
</StackPanel>
Page2 cs:
private void Button_Click(object sender, RoutedEventArgs e)
{
NavigationService nav = NavigationService.GetNavigationService(this);
nav.Navigate(new Uri("Page1.xaml", UriKind.RelativeOrAbsolute));
}

How to navigate to other page with button in WPF

I have a second .xaml page set up under the name Page2.xaml and I want to make it so that when my button is clicked, the user is taken to Page2.xaml
I have this for my button inside of my Page1.xaml:
<Grid>
<Button x:Name="localModeBtn"
Style="{StaticResource MainButtonStyle}"
Content="local mode"
Click="localModeBtn_Click" />
</Grid>
And for the button event handler:
private void localModeBtn_Click(object sender, RoutedEventArgs e)
{
Uri uri = new Uri("Page2.xaml", UriKind.Relative);
this.NavigationService.Navigate(uri);
}
Upon clicking the button I receive an error that says "Cannot locate resource page2.xaml"
The thing is that Page2.xaml is in the same folder as Pag1.xaml so I can't see where I've gone wrong?
Solution to my own question:
I feel a bit silly providing a solution to my own question but thanks to Jasti's link I was able to sort my code out. As he had only posted a comment, I can't mark it as an answer, so here is the solution.
I changed the NavigationWindow to a Window and inserted:
<DockPanel>
<Frame x:Name="_NavigationFrame" NavigationUIVisibility="Hidden" />
</DockPanel>
And within the constructor of the MainWindow.xaml.cs I added:
_NavigationFrame.Navigate(new Page1());
Then the last step was to adjust the button event handler to:
this.NavigationService.Navigate(new Uri("Pages/Page2.xaml", UriKind.Relative));
You should use this, this worked for me:
var Page2= new Page2(); //create your new form.
Page2.Show(); //show the new form.
this.Close(); //only if you want to close the current form.
There is a variable type of a page with the page.xaml right name in your solution.
after that, you should use its methods to do it functionally.
Use any container and bind the content to any property in your viewmodel or codebehind.
After that you just have to update the property by setting a new page and call the PropertyChanged-event (see INotifyPropertyChanged interface). This will update the content of your container and you can display anything you want.
In case you want a separate window
NavigationWindow navWIN = new NavigationWindow();
navWIN.Content = new pageWFbchAdmin();
navWIN.Show();
//winBchAdmin.ShowDialog();
You don't need any C# code for this, just do it in XML:
<Button Content="local mode"
Command="NavigationCommands.GoToPage"
CommandParameter="/Page2.xaml"/>
(Reformatted code not tested)
private void Navigate_Click(object sender, RoutedEventArgs e)//By Prince Jain
{
this.NavigationService.Navigate(new Uri("Page3.xaml", UriKind.Relative));
}
My solution was adding a frame in the main window MainWindow.xaml
<Frame Name="Main" Content="" Margin="127,0,0,0" Background="#FFFFEDED" />
For navigation:
1- Navigating from the main windows on button click:
private void Button_Click(object sender, RoutedEventArgs e)
{
// navigate to pages/projects.xaml inside the main frame
Main.Content = new MyProject.Pages.Projects();
}
2- In case of navigation from the page inside a frame ex Projects.xaml
// declare a extension method in a static class (its your choice if you want to reuse)
// name the class PageExtensions (you can choose any name)
namespace MyProject
{
public static class PageExtensions
{
public static void NavigateTo(this Page page, string path)
{
Frame pageFrame = null;
DependencyObject currParent = VisualTreeHelper.GetParent(page);
while (currParent != null && pageFrame == null)
{
pageFrame = currParent as Frame;
currParent = VisualTreeHelper.GetParent(currParent);
}
if (pageFrame != null)
{
pageFrame.Source = new Uri(path, UriKind.Relative);
}
}
}
}
// to navigate from 'pages/projects.xaml' to another page
// heres how to call the extension on button click
this.NavigateTo("NewProject.xaml");
In addition, you can add another extension method that expects another Page object, in case you want to pass parameters to the constructor
// overloading NavigateTo
public static void NavigateTo(this Page page, Page anotherPage)
{
Frame pageFrame = null;
DependencyObject currParent = VisualTreeHelper.GetParent(page);
while (currParent != null && pageFrame == null)
{
pageFrame = currParent as Frame;
currParent = VisualTreeHelper.GetParent(currParent);
}
// Change the page of the frame.
if (pageFrame != null)
{
pageFrame.Navigate(anotherPage);
}
}
// usage
this.NavigateTo(new Pages.EditProject(id));
First of all, you'll need a frame in your window to hold the pages, so in my MainWindow.xaml I'll add a frame like this:
<Frame x:name="mainFrame"/>
Then We'll add an event listener to our navigation button in our MainWindow.xaml like this:
<Button
x:Name="navBtn"
Content="LIVE VIEW"
Click="NavBtn_Click">
</Button>
Now after we've set our window xaml up, we'll go to MainWindow.xaml.cs and write our code:
//this function should be automatically generated
private void NavBtn_Click(object sender, RoutedEventArgs e)
{
//we'll write this line, which opens our page
mainFrame.Content = new YourPage();
}
and that's it your navigation is ready!
In View (.xaml file):
<StackPanel>
<TextBlock>Outside area of frame</TextBlock>
<StackPanel Height="20" Width="400" VerticalAlignment="Top" Orientation="Horizontal">
<Button Content="Page 1" Width="200" Click="Button_Click"/>
<Button Content="Page 2" Width="200" Click="Button_Click_1"/>
</StackPanel>
<Frame Name="Main" Height="300" Width="700" Background="LightGray">
</Frame>
</StackPanel>
In code behind (.xaml.cs file):
private void Button_Click(object sender, RoutedEventArgs e)
{
Main.Content = new Page1();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
Main.Content = new Page2();
}
Thesse two buttons will now help you to navigate between pages named Page1 and Page2. (Please take care of namespaces if the pages are present in folders or so).

GoBack button doesn't work if there's parameter passed in

I create a very simple project to test navigation. Below are the steps.
Create a Blank App (XAML/C#) project.
Add a Basic Page "PageTwo" to the project.
Add a HyperlinkButton and a TextBox to the MainPage.
In the code-behind of the MainPage, using Frame.Navigate method to navigate to PageTow and pass the TextBox's Text as the parameter.
Override OnNavigatedTo method of the PageTwo to get the passed parameter.
Run the project, input some text to the TextBox and click button to PageTwo, it works well, but if I click the built-in Back Button from PageTwo, I get an exception: Value cannot be null. If I comment the override OnNavigatedTo method, the Back button can lead me to the Main Page without exception.
Anyone can help?
MainPage.xaml:
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<StackPanel>
<TextBox Width="200" Name="TB"/>
<HyperlinkButton Content="Go to PageTwo" Click="HyperlinkButton_Click_1"/>
</StackPanel>
</Grid>
MainPage.xaml.cs:
private void HyperlinkButton_Click_1(object sender, RoutedEventArgs e)
{
Frame.Navigate(typeof(PageTwo), TB.Text);
}
PageTwo.xaml:
<TextBlock Name="TB" Grid.Row="1"/>
PageTwo.xaml.cs:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
TB.Text = e.Parameter as string;
}
In general when overriding any of the UI methods, you need to also call the base.
Your code does not cause an exception if I change the PageTwo.xaml.cs override of OnNavigatedTo to the following:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
TB.Text = e.Parameter as string;
// call base method
base.OnNavigatedTo(e);
}

Categories

Resources