I am trying to open an HTML file in a WebBrowser WPF window using MVVM patten.
Note. I fixed the problems I was getting. Now this code works as desired.
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); } } }
source share