使用MVVM在WPF中显示HTML [英] Displaying HTML in WPF using MVVM
问题描述
我在HTMLReport字段(字段类型为NTEXT)中将HTML源字符串保存在名为Report的SQL Server表中。现在我需要将存储的HTML
显示到WPF窗口中。 HTML标记和内联CSS需要在此WPF窗口中解释。
I have HTML-Source string saved in SQL Server table called "Report" in HTMLReport field (field type is NTEXT). Now I need to display that stored HTML into WPF Window. HTML tags and inline-CSS need to be interpreted on this WPF Window.
有人可以帮我完成这段代码吗?
HTMLView.xaml
Can someone help me to complete this code?
<Window x:Class="MyProject.HTMLView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
Title="HTML View" Height="454" Width="787"
>
<Grid Name="grid1">
<WindowsFormsHost>
<wf:RichTextBox x:Name="reportHTML" Text="{Binding DisplayHTML, Mode=OneWay}"/>
<!-- How do i bind dispaly HTML page here-->
</WindowsFormsHost>
</Grid>
</Window>
HTMLViewModel.cs
HTMLViewModel.cs
namespace MyProject
{
public class HTMLViewModel: ViewModelBase
{
public HTMLViewModel()
{
//Reading from SQL Server table
//SELECT HTMLReport FROM Report WHERE ID=123
//OK, I have HTMLString from database over here
//Now I am assigning that to DisplayHTML Property
DisplayHTML ="<table><tr><td><b>This text should be in table with bold fond </b></td></tr></table>";
}
private string _displayHTML;
public string DisplayHTML
{
get
{
return _displayHTML;
}
set
{
if (_displayHTML!= value)
{
_displayHTML= value;
OnPropertyChanged("DisplayHTML");
}
}
}
}
推荐答案
您可能需要使用 WPF RichTextBox
而不是Winforms。请注意,它的 Document
属性是类型 FlowDocument
。由于您有HTML,因此您需要将HTML转换为 FlowDocument
的方法。 这个问题和答案描述了一种转换方式。
You'll probably want to use a WPF RichTextBox
instead of the Winforms one. Note that its Document
property is of type FlowDocument
. Since you have HTML, you will need a way to convert HTML to a FlowDocument
. This question and answer describe a way to do the conversion.
这篇关于使用MVVM在WPF中显示HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!