gpt4 book ai didi

xaml - 如何在 WPF 中将文本框文本作为超链接

转载 作者:行者123 更新时间:2023-12-04 22:55:05 28 4
gpt4 key购买 nike

我想将文本框文本设为超链接。假设如果键入 www.google.com 作为 tetxbox 文本,当我单击文本时,它会显示在浏览器中打开链接..

我想不出任何想法来实现这个......你能建议我任何想法......我尝试了这两种方法。

方式1:

  <TextBox Grid.Row="4" Name="txtWebPage" VerticalAlignment="Top" TextDecorations="UnderLine" TextChanged="txtWebPage_TextChanged" Foreground="Blue">
</TextBox>

方式2:
 <TextBlock Name="tbWebpage" Grid.Row="4" Background="White" VerticalAlignment="Top" Height="20" >
<Hyperlink></Hyperlink>
</TextBlock>

方式3:
   <RichTextBox Grid.Row="4" Name="rtxtWeb" BorderBrush="Gray" BorderThickness="1" VerticalAlignment="Top" Height="20" IsDocumentEnabled="True" Foreground="Blue" LostFocus="rtxtWeb_LostFocus">
<FlowDocument>
<Paragraph>
<Hyperlink NavigateUri=""/>
</Paragraph>
</FlowDocument>
</RichTextBox>

我不知道如何将 RichTextBox 文本绑定(bind)到超链接 uri! Richtextbox 没有点击事件...任何建议请...

最佳答案

首先,我不确定您为什么要这样做...如果文本在它是有效 URI 的瞬间变成可点击的超链接,您将如何继续编辑它?

Hyperlink 控件不会为您做任何特别的事情,并且它不能托管在 TextBox 中。相反,使用常规的 TextBox,每次更新时检查文本是否有有效的 URI,并应用样式以使文本看起来像可点击的链接。

<TextBox TextChanged="TextBox_TextChanged" MouseDoubleClick="TextBox_MouseDoubleClick">
<TextBox.Style>
<Style TargetType="TextBox">
<Style.Triggers>
<DataTrigger Binding="{Binding HasValidURI}" Value="True">
<Setter Property="TextDecorations" Value="Underline"/>
<Setter Property="Foreground" Value="#FF2A6DCD"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>

每次更改文本时, TextBox_TextChanged叫做。这将使用 Uri.TryCreate() 检查文本是否是有效的 URI。 .如果是这样,属性 HasValidURI设置为 true .一个 DataTriggerTextBox's style 选择了这一点,并使文本带下划线并变为蓝色。

使超链接立即可点击会导致您无法定位光标,因此我注意双击。收到后,再次将文本转换为 URI 并启动 Process使用该 URI。
public partial class MainWindow : Window, INotifyPropertyChanged
{
private bool _hasValidURI;

public bool HasValidURI
{
get { return _hasValidURI; }
set { _hasValidURI = value; OnPropertyChanged( "HasValidURI" ); }
}

public event PropertyChangedEventHandler PropertyChanged;

public void OnPropertyChanged( string name )
{
var handler = PropertyChanged;
if( handler != null ) handler( this, new PropertyChangedEventArgs( name ) );
}

public MainWindow()
{
InitializeComponent();
this.DataContext = this;
}

private void TextBox_TextChanged( object sender, TextChangedEventArgs e )
{
Uri uri;
HasValidURI = Uri.TryCreate( (sender as TextBox).Text, UriKind.Absolute, out uri );
}

private void TextBox_MouseDoubleClick( object sender, MouseButtonEventArgs e )
{
Uri uri;
if( Uri.TryCreate( (sender as TextBox).Text, UriKind.Absolute, out uri ) )
{
Process.Start( new ProcessStartInfo( uri.AbsoluteUri ) );
}
}
}

关于xaml - 如何在 WPF 中将文本框文本作为超链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17660917/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com