Example using Hyperlink in WPF
If you want your application to open the link in a web browser you need to add a HyperLink with the RequestNavigate event set to a function that programmatically opens a web-browser with the address as a parameter.
<TextBlock>
<Hyperlink NavigateUri="http://www.google.com" RequestNavigate="Hyperlink_RequestNavigate">
Click here
</Hyperlink>
</TextBlock>
In the code-behind you would need to add something similar to this to handle the RequestNavigate event:
private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
{
// for .NET Core you need to add UseShellExecute = true
// see https://learn.microsoft.com/dotnet/api/system.diagnostics.processstartinfo.useshellexecute#property-value
Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
e.Handled = true;
}
In addition you will also need the following imports:
using System.Diagnostics;
using System.Windows.Navigation;
It will look like this in your application:
How to make a simple hyperlink in XAML?
You can use a Button with a custom control template, the code below is a limited hyperlink style button (for example it only support textual hyperlinks) but maybe it'll point you in the right direction.
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Page.Resources>
<Style x:Key="Link" TargetType="Button">
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="HorizontalAlignment" Value="Center"/>
<Setter Property="Cursor" Value="Hand"/>
<Setter Property="Foreground" Value="Blue"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<TextBlock TextDecorations="Underline"
Text="{TemplateBinding Content}"
Background="{TemplateBinding Background}"/>
<ControlTemplate.Triggers>
<Trigger Property="IsPressed" Value="True">
<Setter Property="Foreground" Value="Red"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Page.Resources>
<Button Content="Click Me!" Style="{StaticResource Link}"/>
</Page>
construct hyperlink in wpf C#
Try to use Inlines to add Hyperlink to TextBlock and to add text to HyperLink
TextBlock textBlock = new TextBlock();
Hyperlink link = new Hyperlink();
link.Inlines.Add("Click me");
textBlock.Inlines.Add(link);
c# - itemsource text to hyperlink
How about using a Hyperlink in the ItemTemplate of the ItemsControl as follows:
<ItemsControl ItemsSource="{Binding LinkList}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock>
<Hyperlink NavigateUri="{Binding Link}" RequestNavigate="Hyperlink_RequestNavigate">
<TextBlock Text="{Binding Link}" />
</Hyperlink>
</TextBlock>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
As you can see, there is also an event on the Hyperlink, "RequestNavigate", which has a handler in code behind as follows:
private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
{
System.Diagnostics.Process.Start(e.Uri.AbsoluteUri);
e.Handled = true;
}
Alternatively of course, you could bind the Command of the Hyperlink to carry out the navigation using the MVVM pattern.
Hope that helps.
C# WPF Text with links
You can use the Hyperlink class. It's a FrameworkContentElement, so you can use it in a TextBlock or FlowDocument or anywhere else you can embed content.
<TextBlock>
<Run>Text</Run>
<Hyperlink NavigateUri="http://stackoverflow.com">with</Hyperlink>
<Run>some</Run>
<Hyperlink NavigateUri="http://google.com">hyperlinks</Hyperlink>
</TextBlock>
You may want to look at using a RichTextBox as part of your editor. This will host a FlowDocument, which can contain content such as Hyperlinks.
Update: There are two ways to handle clicks on the Hyperlink. One is to handle the RequestNavigate event. It is a Routed Event, so you can either attach a handler to the Hyperlink itself or you can attach one to an element higher in the tree such as the Window or the RichTextBox:
// On a specific Hyperlink
myLink.RequestNavigate +=
new RequestNavigateEventHandler(RequestNavigateHandler);
// To handle all Hyperlinks in the RichTextBox
richTextBox1.AddHandler(Hyperlink.RequestNavigateEvent,
new RequestNavigateEventHandler(RequestNavigateHandler));
The other way is to use commanding by setting the Command property on the Hyperlink to an ICommand implementation. The Executed method on the ICommand will be called when the Hyperlink is clicked.
If you want to launch a browser in the handler, you can pass the URI to Process.Start:
private void RequestNavigateHandler(object sender, RequestNavigateEventArgs e)
{
Process.Start(e.Uri.ToString());
}
Simple implementation of a textblock or textfield or richtext that allows a URL in WPF using C#
The way I've implemented hyperlinks in the past is to create a attached property, which you can add onto the Hyperlink
, which will handle the RequestNavigate
itself.
For example:
namespace WpfDemo.Extensions
{
public static class HyperlinkExtensions
{
public static bool GetIsExternal(DependencyObject obj)
{
return (bool)obj.GetValue(IsExternalProperty);
}
public static void SetIsExternal(DependencyObject obj, bool value)
{
obj.SetValue(IsExternalProperty, value);
}
public static readonly DependencyProperty IsExternalProperty =
DependencyProperty.RegisterAttached("IsExternal", typeof(bool), typeof(HyperlinkExtensions), new UIPropertyMetadata(false, OnIsExternalChanged));
private static void OnIsExternalChanged(object sender, DependencyPropertyChangedEventArgs args)
{
var hyperlink = sender as Hyperlink;
if ((bool)args.NewValue)
hyperlink.RequestNavigate += Hyperlink_RequestNavigate;
else
hyperlink.RequestNavigate -= Hyperlink_RequestNavigate;
}
private static void Hyperlink_RequestNavigate(object sender, System.Windows.Navigation.RequestNavigateEventArgs e)
{
ProcessStartInfo psi = new()
{
FileName = e.Uri.AbsoluteUri,
UseShellExecute = true,
};
Process.Start(psi);
e.Handled = true;
}
}
}
The code defines an attached property that when you add to a Hyperlink
, will handle the logic for navigating to the links for you.
You can use the following code the following way:
<Window
x:Class="WpfDemo.MainWindow"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:helper="clr-namespace:WpfDemo.Extensions"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Grid>
<TextBlock>
<Hyperlink helper:HyperlinkExtensions.IsExternal="true" NavigateUri="https://google.com">
Google Link
</Hyperlink>
</TextBlock>
</Grid>
</Window>
Add hyperlink to textblock WPF
You can use Regex with a value converter in such situation.
Use this for your requirements (original idea from here):
private Regex regex =
new Regex(@"\[a\s+href='(?<link>[^']+)'\](?<text>.*?)\[/a\]",
RegexOptions.Compiled);
This will match all links in your string containing links, and make 2 named groups for each match : link
and text
Now you can iterate through all the matches. Each match will give you a
foreach (Match match in regex.Matches(stringContainingLinks))
{
string link = match.Groups["link"].Value;
int link_start = match.Groups["link"].Index;
int link_end = match.Groups["link"].Index + link.Length;
string text = match.Groups["text"].Value;
int text_start = match.Groups["text"].Index;
int text_end = match.Groups["text"].Index + text.Length;
// do whatever you want with stringContainingLinks.
// In particular, remove whole `match` ie [a href='...']...[/a]
// and instead put HyperLink with `NavigateUri = link` and
// `Inlines.Add(text)`
// See the answer by Stanislav Kniazev for how to do this
}
Note : use this logic in your custom ConvertToHyperlinkedText
value converter.
Edit HyperLink NavigationURI WPF
Put a Run
element inside the Hyperlink
and set the Text
property of this one:
<TextBlock x:Name="LinkToQuery" Grid.Row="39" Grid.Column="1" Grid.ColumnSpan="4" Margin="10">
<Hyperlink x:Name="URLQuery" RequestNavigate="Hyperlink_RequestNavigate" Foreground="Blue">
<Run x:Name="linkText" Text="Selected: A" />
</Hyperlink>
</TextBlock>
private void component_ComboBox_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
string selectedComponent = box_ComboBox.SelectedItem.ToString();
linkText.Text = string.Format("Selected: {0} ", selectedComponent);
URLQuery.NavigateUri = new System.Uri(LinkQuery[selectedComponent], System.UriKind.Absolute);
}
WPF hyperlink in RichTextBox click event
Set
richTextBox.IsDocumentEnabled = true
hold down Ctrl key and Click on the Hyperlink. It should work.
See this post if you don't like to hold the Ctrl down.
Related Topics
What Is the Max Limit of Data into List<String> in C#
Should You Implement Idisposable.Dispose() So That It Never Throws
Ziparchive Creates Invalid Zip File
String Interning in .Net Framework - What Are the Benefits and When to Use Interning
C#: Should Object Variables Be Assigned to Null
How to Create a Datatable in C# and How to Add Rows
What Is the Point of Lookup<Tkey, Telement>
Differences Between Iqueryable, List, Ienumerator
What Is the Use for Task.Fromresult<Tresult> in C#
How to List the Contents of a .Zip Folder in C#
Make ASP.NET Wcf Convert Dictionary to JSON, Omitting "Key" & "Value" Tags
Deserialize Nested JSON into C# Objects
How to Dispose My Filestream When Implementing a File Download in ASP.NET
Force Browser to Download PDF Document Instead of Opening It
Converting from Ienumerable to List