c# - 使用转换器创建标记扩展

标签 c# wpf converters markup-extensions

我正在尝试创建一个标记扩展,它将采用 HTML 字符串,将其转换为 FlowDocument,然后返回 FlowDocument。我对创建标记扩展相当陌生,我希望这对有更多经验的人来说是显而易见的。这是我的代码:

[MarkupExtensionReturnType(typeof(FlowDocument))]
public class HtmlToXamlExtension : MarkupExtension
{
    public HtmlToXamlExtension(String source)
    {
        this.Source = source;
    }

    [ConstructorArgument("source")]
    public String Source { get; set; }

    public Type LocalizationResourceType { get; set; }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        if (this.Source == null)
        {
            throw new InvalidOperationException("Source must be set.");
        }

        FlowDocument flowDocument = new FlowDocument();
        flowDocument.PagePadding = new Thickness(0, 0, 0, 0);
        string xaml = HtmlToXamlConverter.ConvertHtmlToXaml(Source.ToString(), false);

        using (MemoryStream stream = new MemoryStream((new ASCIIEncoding()).GetBytes(xaml)))
        {
            TextRange text = new TextRange(flowDocument.ContentStart, flowDocument.ContentEnd);
            text.Load(stream, DataFormats.Xaml);
        }

        return flowDocument;
    }
}

更新:这是 XAML。

<RadioButton.ToolTip>
    <FlowDocumentScrollViewer Document="{ext:HtmlToXaml Source={x:Static res:ExtrudeXaml.RadioButtonCreateBody_TooltipContent}}" ScrollViewer.VerticalScrollBarVisibility="Hidden" />
</RadioButton.ToolTip>

还有我的 VS 错误列表:

  • 解析标记扩展时遇到类型“MS.Internal.Markup.MarkupExtensionParser+UnknownMarkupExtension”的错误 3 未知属性“Source”。第 89 行第 49 位。
  • 错误 1 ​​“HtmlToXamlExtension”类型不包含具有指定数量参数的构造函数。
  • 错误 2 “HtmlToXamlExtension”类型的构造函数没有 0 个参数。

最佳答案

您在没有默认构造函数的情况下实现了 MarkupExtension: 所以你有两个选择:

  1. 删除你的特定构造函数(无论如何你设置Source 直接)
  2. 更改对 HtmlToXamlExtension 的调用,如果您删除 Source= 部分,则 Wpf 将尝试在 ext 之后立即查找匹配所有未命名字段的构造函数: HtmlToXaml部分:

    <RadioButton.ToolTip>
      <FlowDocumentScrollViewer 
             Document="{ext:HtmlToXaml {x:Static res:ExtrudeXaml.RadioButtonCreateBody_TooltipContent}}" 
             ScrollViewer.VerticalScrollBarVisibility="Hidden" />
    </RadioButton.ToolTip>
    

    UPD:尽管它有效,但 MSDN 表示,you should have default constructor

希望对您有所帮助。

关于c# - 使用转换器创建标记扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17211862/

相关文章:

c# - 在 MonthCalendar 中选择特定日期时如何删除项目

c# - 是否可以从 Excel 电子表格 (VBA) 中获取 WinForms "Button"?

c# - C# 中的日期时间格式

java - Vaadin:为 ListSelect 使用自定义转换器

c# - 即使将身份验证模式设置为 'Windows',ASP.Net MVC4 User.Identity.Name 也会变空

c# - 有关 Vault.dll 和 Vaultcli.dll 的信息

.net - WPF 窗口类的 IDisposable 成员

wpf - wpf数据网格中的绑定(bind)组合框

c# - 如何在 ASP.NET MVC 中即时将 HTML 转换为 Word 文档?

javascript - 你能将一个变量除/乘另一个数字四舍五入到最接近的百分之几吗?