【问题标题】:String that has an xaml element form from C# to XAML code具有从 C# 到 XAML 代码的 xaml 元素形式的字符串
【发布时间】:2022-01-08 22:02:01
【问题描述】:

我正在尝试传递一个包含超链接的 textBlock。像这样的:

 string textblock = "<TextBlock>Hello<Hyperlink NavigateUri="https://google.com"RequestNavigate="Hyperlink_RequestNavigate">Click</Hyperlink></TextBlock>"

我想在不使用对象实例的情况下将该字符串传递到网格中。我阅读了有关 xaml 阅读器、加载器的信息,但我无法弄清楚...

我的 xaml 看起来像这样:

      <Window x:Class="DailyText.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"
        Title="any" Height="450" Width="800" >
    <Grid>
        
    </Grid>
    </Window>

【问题讨论】:

  • 即使使用 XamlParser 也会创建一个对象,您必须将其添加到 Grid 的 Children 集合中。您应该简单地创建一个 TextBlock 并为其内联分配一个超链接。
  • 谢谢。但是你知道我应该如何将 XamlParser 创建的对象添加到网格的 Children 集合中?

标签: c# wpf data-binding


【解决方案1】:

试试看下面的代码是否符合你的需要。

Xaml:

<Grid x:Name="grid">
        <TextBlock Name="TextBlockWithHyperlink" Background="Orange" Width="100" Height="50" HorizontalAlignment="Left">
          Hello
            <Hyperlink   NavigateUri="https://google.com" RequestNavigate="Hyperlink_RequestNavigate">
                Click
            </Hyperlink>
        </TextBlock>
    </Grid>

xaml.cs:

  public partial class MainWindow : Window
  {
    public MainWindow()
    {
      InitializeComponent();

      TextBlock tb = new TextBlock();
      Hyperlink link=new Hyperlink() { NavigateUri=new Uri("https://google.com") };
      link.Inlines.Add("click");
      link.RequestNavigate+= Hyperlink_RequestNavigate;
      tb.Inlines.Add("Hello");
      tb.Inlines.Add(link);
      tb.Height=60;
      tb.Background=Brushes.LightSeaGreen;
      tb.HorizontalAlignment= HorizontalAlignment.Center; 
      grid.Children.Add(tb);
    }

    private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
    {
      System.Diagnostics.Process.Start(e.Uri.ToString());
    }

  }

【讨论】:

  • 谢谢你的帮助......但它对我没有帮助......我抓取了一些包含超链接的文本,但我无法处理它......我抓取了 innerHtml 并转换为 xaml 和然后我想把它推到网格上
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-09
  • 1970-01-01
相关资源
最近更新 更多