作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想将文本框文本设为超链接。假设如果键入 www.google.com 作为 tetxbox 文本,当我单击文本时,它会显示在浏览器中打开链接..
我想不出任何想法来实现这个......你能建议我任何想法......我尝试了这两种方法。
方式1:
<TextBox Grid.Row="4" Name="txtWebPage" VerticalAlignment="Top" TextDecorations="UnderLine" TextChanged="txtWebPage_TextChanged" Foreground="Blue">
</TextBox>
<TextBlock Name="tbWebpage" Grid.Row="4" Background="White" VerticalAlignment="Top" Height="20" >
<Hyperlink></Hyperlink>
</TextBlock>
<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>
最佳答案
首先,我不确定您为什么要这样做...如果文本在它是有效 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
.一个
DataTrigger
在
TextBox's
style 选择了这一点,并使文本带下划线并变为蓝色。
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/
我是一名优秀的程序员,十分优秀!