[C# WPF] 多言語対応がうまくいかないのでハイパーリンクを自作した
.NETにはHyperlinkクラスがありますが、NavigateUriに設定するURLを言語ごとに切り替えようとStaticResourceを指定したところ実行時エラーになるので、それっぽくうごくボタンを作りました。
文章中の一部をハイパーリンクにする場合は別の方法になるので、単独で配置したいときの参考になるかもしれません。

環境
- Windows 10
- Visual Studio 2022
- .NET 6.0
機能
- マウスオーバーすると色が変わって、アンダースコアが消えます
- クリックすると既定のブラウザで設定したURLを開きます
コード
ソリューション構成とリソースはこんな感じです。

MainWindow.xaml
<Window x:Class="Sample_HyperlinkButton.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:properties="clr-namespace:Sample_HyperlinkButton.Properties"
mc:Ignorable="d"
Title="MainWindow" Height="250" Width="400"
WindowStartupLocation="CenterOwner" ResizeMode="NoResize" ShowInTaskbar="False"
>
<Grid>
<Button HorizontalAlignment="Center" VerticalAlignment="Center"
HorizontalContentAlignment="Center" VerticalContentAlignment="Center"
Content="{x:Static properties:Resources.Caption}"
Click="OnClick"
>
<Button.Style>
<Style TargetType="Button">
<Setter Property="OverridesDefaultStyle" Value="True"/>
<Setter Property="Foreground" Value="Blue"/>
<Setter Property="TextBlock.TextDecorations" Value="Underline"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<TextBlock Name="TextBlock" TextDecorations="Underline" Text="{TemplateBinding Content}" Background="{TemplateBinding Background}"/>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="TextBlock" Property="TextBlock.TextDecorations" Value="{x:Null}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Foreground" Value="Aqua"/>
</Trigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
</Grid>
</Window>
MainWindow.xaml.cs
namespace Sample_HyperlinkButton
{
using System.Windows;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void OnClick(object sender, RoutedEventArgs e)
{
var startInfo = new System.Diagnostics.ProcessStartInfo(Properties.Resources.URL)
{
UseShellExecute = true
};
_ = System.Diagnostics.Process.Start(startInfo);
}
}
}
おしまい。





ディスカッション
コメント一覧
まだ、コメントがありません