我想從我的 HTML 頁面讀取文本并將其顯示到我的 WPF 應用程式中的標簽或文本塊中。我怎么做?
使用 Windows 表單,我是這樣做的:
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
WebBrowser1.Navigate("C:\Users\Test\Desktop\Webseite\test.htm")
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim ImageInhalt As String
Label1.Text = WebBrowser1.Document.GetElementById("mytext").GetAttribute("value")
ImageInhalt = WebBrowser1.Document.GetElementById("mytext2").GetAttribute("value")
If ImageInhalt.Contains("STOP") Then
PictureBox1.Image = My.Resources._stop
End If
End Sub
End Class
HTML 頁面 (test.htm)
<input type="text" name="userInfoNav" value="Hallo"/><br/>"
現在非常感謝您的幫助
uj5u.com熱心網友回復:
您必須將 URL 或檔案的 HTML 內容加載到mshtml.HTMLDocument. 然后,您可以使用類似 JavaScript 的語法處理 DOM 物件。
需要參考Microsoft.mshtml.dll。
C#
partial class MainWindow : Window
{
private mshtml.HTMLDocument HtmlDocument { get; set; }
public async Task SetTextBoxTextAsync(string filePath, string id)
{
await UpdateHtmlDocumentAsync(filePath);
string value = GetHtmlElementValueById(id);
this.TextBlock.Text = value;
}
private async Task UpdateHtmlDocumentAsync(string filePath)
{
string htmlContent = await File.ReadAllLinesAsync(filePath);
this.HtmlDocument = new HTMLDocument();
(this.HtmlDocument as IHTMLDocument2).write(htmlContent);
}
private string GetHtmlElementValueById(string elementId)
=> this.HtmlDocument.getElementById(elementId).innerText;
}
VB.NET
Partial Class MainWindow
Inherits Window
Private Property HtmlDocument As mshtml.HTMLDocument
Private Async Function SetTextBoxTextAsync(ByVal filePath As String, ByVal id As String) As Task
Await UpdateHtmlDocumentAsync(filePath)
Dim value As String = GetHtmlElementValueById(id)
Me.TextBlock.Text = value
End Function
Public Async Function UpdateHtmlDocumentAsync(ByVal filePath As String) As Task
Dim htmlContent As String = Await File.ReadAllLinesAsync(filePath)
Me.HtmlDocument = New HTMLDocument()
(TryCast(Me.HtmlDocument, IHTMLDocument2)).write(htmlContent)
End Function
Public Function GetHtmlElementValueById(ByVal elementId As String) As String
Return Me.HtmlDocument.getElementById(elementId).innerText
End Function
End Class
評論
如果您對呈現內容感興趣,請使用該WebBrowser控制元件。它有一個Document屬性,您可以將其轉換為mshtml.HTMLDocument. 由于WebBrowser是一個沉重的實體,您應該只在您打算呈現 HTML 時使用它。否則,mshtml.HTMLDocument如上所示手動構建。
uj5u.com熱心網友回復:
您可以將 html 加載到TextBlock這樣的位置:
TextBlock1.Text = System.IO.File.ReadAllText("C:\Users\Test\Desktop\Webseite\test.htm")
我假設TextBlock被命名為:TextBlock1。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/415369.html
標籤:
上一篇:基于組合框選定項填充datagridview,該組合框取決于資料庫中另一個選定的組合框
下一篇:如何將屬性恢復為其默認值?
