WPF - TextBlock 文本 + 超链接

如何从 C# 代码生成此 xaml:

目前:

<TextBlock>
    Click <Hyperlink Command="{Binding MyCommand}">here</Hyperlink> to continue.
</TextBlock>

我想要的:

<TextBlock Text="{Binding MyTextWithHyperlink, Mode=OneWay}" />

public string MyTextWithHyperlink
{
    get
    {
        return ""; //???
    }
}


是的,我有充分的理由以这种方式而不是在 xaml 中这样做。 :)

更新:这就是我要返回字符串的原因,因为 IDataError 返回一个字符串...

String IDataError.this[String columnName]
{
    get
    {
        if (columnName == "MyProperty")
        {
            if (something1) return ""; //????
            if (something2) return "some other string";
        }

        return null;
    }
}

最佳答案

不幸的是,没有简单的方法来做到这一点......据我所知,你能做的最好的事情就是返回一个 XAML 字符串并使用转换器来解析它。

警告:前面的代码丑陋...

XAML

<Window.Resources>
    <local:XamlToTextBlockConverter x:Key="xamlConverter" />
</Window.Resources>
<Grid>
    <ContentControl Content="{Binding MyTextWithHyperlink, Converter={StaticResource xamlConverter}}" />
</Grid>

转换器

public class XamlToTextBlockConverter : IValueConverter
{
    #region Implementation of IValueConverter

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        string xaml = value as string;
        if (xaml == null)
            return Binding.DoNothing;

        const string textBlockFormat =
            @"<TextBlock xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"">{0}</TextBlock>";
        string fullXaml = string.Format(textBlockFormat, xaml);

        return (TextBlock)XamlReader.Parse(fullXaml);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}

View 模型

public string MyTextWithHyperlink
{
    get { return "Click <Hyperlink Command=\"{Binding MyCommand}\">here</Hyperlink> to continue"; }
}

请注意使用 ContentControl 而不是 TextBlock:这是因为 TextBlock.Text 属性只能包含纯文本,不能包含格式化文档,并且 Inlines 属性无法绑定(bind),因为它不是依赖属性(无论如何它是只读的)。相反,我们在转换器中手动创建一个 TextBlock 并将其分配给 ContentControl 的内容。

这绝对不是一个非常优雅的解决方案,但它确实有效......

https://stackoverflow.com/questions/5953499/

相关文章:

qt - PyQt - 如何导入 .qss 文件?

asp.net - ObjectDataSource 没有要插入的值

performance - C# 和 C++ 可以互操作高性能代码吗?

php - 尝试在 php 中为在线商店实现促销代码框

sql-server - SQL Server 复制数据库问题

sql-server - SQL 服务器 : select without order

php - 如何确定哪些脚本正在使用 fopen?

.net - "Statement is not valid in a namespace"错误信息

php - 在 url mod_rewrite 中隐藏扩展名 .php

.net - 转义中间字符串百分号,正则表达式是最好的选择吗?