使用web浏览器控件更改转换为字符串的html内容的字体



我正在使用它将HTML内容转换为XAML,但我需要更改内容的字体大小。所以,我试图用这个来改变字体大小,但我得到了doc作为null。知道为什么吗?

这是我的代码-

public static void DocumentPropertyChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
{
WebBrowser browser = target as WebBrowser;
var doc = browser.Document as HTMLDocument;
if (browser != null)
{
string document = e.NewValue as string;
browser.NavigateToString(document);
}
if (doc != null)
{
doc.execCommand("FontSize", false, 12);
doc.execCommand("FontFamily", false, "Arial");
}
}

试试这个:

public static void DocumentPropertyChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
{
if (!(target is WebBrowser)) // Handles null and other weird things.
throw new Exception("target is not a WebBrowser!");
WebBrowser browser = target as WebBrowser;
string document = e.NewValue as string;
if (document == null)
throw new Exception("e.NewValue is not a string!");
browser.NavigateToString(document);
var doc = browser.Document as HTMLDocument;
if (doc != null)
{
doc.execCommand("FontSize", false, 12);
doc.execCommand("FontFamily", false, "Arial");
}
else
{
throw new Exception("browser.Document is not an HTMLDocument!");
}
}

我认为这需要引用Microsoft.mshtml.dll和using mshtml;语句,如果您还没有这样做的话。

我已经添加了所有的投掷,因为没有运行此代码,我不能100%确定问题所在。

因此,就其价值而言,我希望这能有所帮助。

编辑

文档说明NavigateToString异步加载内容

通过在导航后分配doc,上面的代码会出现,用于非常短的文档,但这是不可信的。导航前指定doc不起作用。

更好的解决方案可能是处理WebBrowser.Navigated事件,以确保在与WebBrowser.Document属性交互之前内容已完全加载:

XAML:

<WebBrowser Name="browser" Navigated="Browser_Navigated"/>

CS:

public static void DocumentPropertyChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
{
WebBrowser browser = target as WebBrowser;
if (browser != null)
{
string document = e.NewValue as string;
browser.NavigateToString(document);
}
}
private void Browser_Navigated(object sender, NavigationEventArgs e)
{
var doc = webBrowser.Document as HTMLDocument;
if (doc != null)
{
doc.execCommand("FontSize", false, 12);
doc.execCommand("FontFamily", false, "Arial");
}
}

注意:此代码将在加载到WebBrowser中的每个文档上运行您的execCommand(我还没有测试btw(。如果这是一个问题,我们可以解决。

最新更新