使用MVVM模式在WPF中实现WebBrowser

8

我正在尝试使用MVVM模式在WPF的WebBrowser窗口中打开HTML文件。

注意:我已经解决了之前遇到的问题。现在这段代码已经按照预期工作。

ViewHTMLPageView.xaml

 <Window x:Class="MyProject.ViewHTMLPageView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:MyProject.Utility"
    Title="HTML Report" Height="454" Width="787"
    >
    <Grid Name="grid1">
      <WebBrowser local:WebBrowserUtility.BindableSource="{Binding ReportPage}"  />
    </Grid>
</Window>

ViewHTMLPageViewModel.cs

 namespace MyProject
 {
   public class ViewHTMLPageViewModel: ViewModelBase
   {
    public ViewHTMLPageView()
    {
         //Testing html page on load 
        _reportPage = "<table border='5'><tr><td> This is sample <b> bold </b></td></tr></table>";
        OnPropertyChanged("ReportPage");
    }

    private string _reportPage;
    public string ReportPage
    {
        get
        {
            return _reportPage;
        }

        set
        {
            if (_reportPage != value)
            {
                _reportPage = value;
                OnPropertyChanged("ReportPage");
            }
        }
    }
 }

WebBrowserUtility.cs

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Windows.Controls; 
 using System.Windows;

 namespace MyProject.Utility
 {
   public static class WebBrowserUtility
   {
    public static readonly DependencyProperty BindableSourceProperty = 
                           DependencyProperty.RegisterAttached("BindableSource", typeof(string), 
                           typeof(WebBrowserUtility), new UIPropertyMetadata(null, 
                           BindableSourcePropertyChanged));

    public static string GetBindableSource(DependencyObject obj)
    {
        return (string)obj.GetValue(BindableSourceProperty);
    }

    public static void SetBindableSource(DependencyObject obj, string value)
    {
        obj.SetValue(BindableSourceProperty, value);
    }

    public static void BindableSourcePropertyChanged(DependencyObject o, 
                                                     DependencyPropertyChangedEventArgs e)
    {
        var webBrowser = (WebBrowser)o;
        webBrowser.NavigateToString((string)e.NewValue);
    }
   }
 }
1个回答

8
在WebBrowserUtility.cs文件中,更改以下语句:
using System.Windows.Forms;

为了

using System.Windows.Controls;

现在,就您的问题而言,“+1”是什么意思?您能告诉我为什么这会解决您的问题吗?

我喜欢增加挑战的想法 :) - Steve Greatrex
好的,你的建议解决了错误信息的问题。 现在我遇到了BindableSource="{Binding WebAddress}"的问题, 它无法与WebBrowserUtility通信。 有什么建议吗? - Shai
1
你需要做的第一件事是打开数据绑定的调试信息:http://i.stack.imgur.com/MF8i5.png 接下来,重新运行并检查输出窗口,看看有什么错误。最后,提出另一个问题,并附上你发现的所有细节。 - user1228
@Will 选我!因为 OP 不是使用 Windows Forms,而是使用 WPF。哈哈,失败了。不知道数据绑定的调试消息。希望他们也有 WP7 的调试消息。 - Terrance

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接