【问题标题】:How to make the URL in textblock be clickable?如何使文本块中的 URL 可点击?
【发布时间】:2010-12-10 08:39:20
【问题描述】:

文本块的内容是从网络服务导入的,但不知何故有一个 URL。

可以做个链接吗?

谢谢。

【问题讨论】:

标签: silverlight


【解决方案1】:

听起来你想要a LinkLabel control。我在Silverlight Twitter Badge 中使用了该控件并进行了一些修改,以混合显示在推文中的文本和链接。

如果您只有一个带有链接的 TextBlock 并且希望该可点击,那么您只需将光标设置为手并为 MouseLeftButtonDown 事件添加一个事件处理程序,该事件将导航到 TextBox 的值。

Xaml:

<TextBlock Text="http://www.microsoft.com" Cursor="Hand" TextDecorations="Underline" MouseLeftButtonDown="TextBlock_MouseLeftButtonDown" />

代码:

private void TextBlock_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    var txt = ((TextBlock)sender).Text;
    System.Windows.Browser.HtmlPage.Window.Navigate(new Uri(txt, UriKind.Absolute));
}

【讨论】:

    【解决方案2】:

    您可以执行以下操作;但是,这使用了标签而不是文本块。

    在您的 XAML 中,您执行以下操作:

    <dataInput:Label Grid.Row="2">
                    <ContentPresenter>
                        <StackPanel Orientation="Horizontal">
                            <TextBlock Text="Hello world"/>
                            <HyperlinkButton x:Name="Test" NavigateUri="{Binding Path=URI}" Content="This is a url"/>
                        </StackPanel>
                    </ContentPresenter>
                </dataInput:Label>
    

    并在您后面的代码中添加以下依赖项属性并将数据上下文设置为页面本身

    public static readonly DependencyProperty URLProperty =
                DependencyProperty.Register("URI", typeof(Uri), typeof(MainPage), null);
    
            public Uri URI { get
                {
                    return (Uri)GetValue(URLProperty);
                }
                set
                { SetValue(URLProperty, value); }
            }
    

    此代码设置绑定到 URL 的依赖属性;

    public MainPage()
            {
                InitializeComponent();
                URI = new Uri("/Home", UriKind.Relative);
                DataContext = this;
            }
    

    此代码创建一个新的 URI 并将其绑定到变量。它还将数据上下文设置为页面本身。

    【讨论】:

      猜你喜欢
      • 2010-12-27
      • 1970-01-01
      • 1970-01-01
      • 2011-05-31
      • 1970-01-01
      • 1970-01-01
      • 2014-03-31
      • 1970-01-01
      • 2022-07-28
      相关资源
      最近更新 更多