【问题标题】:Replace text with control markup using Visual Studio macro使用 Visual Studio 宏将文本替换为控件标记
【发布时间】:2012-01-10 20:24:15
【问题描述】:

我正在尝试使用 Visual Studio (2010) 宏将 ASPX 页面中的某些文本替换为文字控件,但似乎控件标记在替换时正在被修改。

我有一个包含以下内容的 ASPX 页面:

<span>Foo</span>

我要替换为:

<span><asp:Literal Text="<%$ Resources:Foo %>" runat="server" /></span>

这是通过突出显示“Foo”文本然后运行宏来替换文本来完成的。但是,在执行宏时,Visual Studio 并没有完全按照输入的方式粘贴文本。

我的宏代码如下所示:

Dim Selection As TextSelection = DTE.ActiveDocument.Selection
Selection.Text = "<asp:Literal Text=""<%$ Resources:Foo %>"" runat=""Server""/>"

但是,当宏执行时,它会插入:

<asp:Literal Text=""<%$ Resources:Foo %>" runat="Server" /> %>"

请注意第一组双引号(尽管其他双引号是正确的),并在末尾添加了额外的%&gt;"。如果替换文本包含任何引号,这似乎会发生。例如,如果我只是尝试将选定的文本替换为&lt;asp:Literal runat=Server"/&gt;,它就可以正常工作。

有谁知道为什么会这样,我该如何解决这个问题?

谢谢。

【问题讨论】:

    标签: visual-studio visual-studio-2010 macros replace


    【解决方案1】:

    最终找到了解决方案,尽管它更像是一种解决方法。奇怪的行为似乎部分是由 Visual Studio 中的“粘贴时格式化代码”设置引起的,当禁用该设置时,修复了双引号问题,而不是最后添加的额外标记。

    为了解决这个问题,我现在用随机字符串替换文本,然后用新文本重写文件。这样做的缺点是 Visual Studio 会抛出一个提示,说明文件已更改并询问是否应该重新加载,需要这样做才能看到更新,但至少实际文件内容现在是正确的。

    代码如下所示(为本示例进行了简化):

    Sub ReplaceText()
    
        'This is the markup we want to replace our selection with
        Dim LiteralMarkup As String = "<asp:Literal Text=""<%$ Resources:Foo %>"" runat=""Server""/>"
    
        'Generate random GUID to do initial replace
        Dim RandomGuid As String = Guid.NewGuid().ToString()
    
        'Now replace the selection with the generated guid
        DTE.ActiveDocument.Selection.Text = RandomGuid
    
        'Save the file
        DTE.ActiveDocument.Save()
    
        'Now replace the generated guid with the real markup that we want
        Dim NewText As String = File.ReadAllText(DTE.ActiveDocument.FullName).Replace(RandomGuid, LiteralMarkup)
    
        'Rewrite the file (will cause VS to prompt user to reload file)
        File.WriteAllText(CurrentPath, NewText)
    
    End Sub
    

    这不是一个理想的解决方案,但可以解决问题。

    对于任何感兴趣的人,此代码用于宏中,该宏旨在简化将文本从 aspx 或 ascx 文件移动到资源文件的过程。完整代码在这里:https://gist.github.com/1591239

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多