2010-10-12 24 views
5

OK, así que pensé que esto sería realmente simple aunque recién lo había hecho anteriormente cuando trabajaba con archivos de recursos de proyecto de WPF.Cargue un recurso de proyecto en un control WPF Webbrowser

Cuando se inicia mi aplicación, quiero cargar un archivo html local (enviado con la aplicación) en el control Webbrowser. ¡Sin embargo no puedo encontrar una manera fácil de hacer esto! ¿Algunas ideas?

Respuesta

4

regresado esto al final cambie la acción de compilación del archivo a 'Copiar siempre' y entonces usando Environment.CurrentDirectory para obtener el directorio de la aplicación:

string appDir = Environment.CurrentDirectory; 
Uri pageUri = new Uri(appDir + "/page.html"); 
myWebBrowser.Source = pageUri; 

que parece funcionar bien.

7

Acabo de encontrar este mismo problema. Tenía la esperanza de simplemente hacer esto:

<WebBrowser x:Name="myWebBrowser" Source="page.html"/> 

Pero en cambio, me sale este error:

Relative URIs are not allowed. Parameter name: source

Así que eso es molesto. En su lugar, terminé con una solución muy similar a la suya en el código detrás:

myWebBrowser.Source = new Uri(new System.IO.FileInfo("page.html").FullName); 

estoy seguro de que hay algún método de kung-fu XAML contorsionista con la que conseguir alrededor de ese tema, pero no tengo ni idea de lo que es.^_^

2

Llegó tarde al espectáculo, pero me encontré con esto cuando estaba buscando lo mismo. Lo tengo para trabajar de una manera más WPF. WebBrowser tiene un método NavigateToStream() por lo que simplemente puede establecer la secuencia de recursos.

StreamResourceInfo info = Application.GetResourceStream(new Uri("Page.html", UriKind.Relative)); 
if (info != null) 
    myWebBrowser.NavigateToStream(info.Stream); 

De esta manera, se puede conservar un recurso y que no tiene que copiar en el disco.

0

envolví esto en un control de usuario para hacer frente a algunos de los problemas con el control WebBrowser .. Establecer la 'Acción de generación' propiedad de las páginas HTML, y cualquier contenido incorporado a 'contenido' y la 'Copia de salida Directorio 'a' Copiar si es nuevo '. Mantenga cualquier jerarquía de recursos de página en html como lo haría normalmente en un servidor. En el modelo de vista, o de código subyacente, que acaba de establecer uno de los HtmlUri, HtmlString o propiedades HtmlStream de este control (también se puede desactivar el sonido de clic molesto; o) ..

Ejemplo Uri:

public Uri DefaultUri 
{ 
    get { return new Uri(@"pack://siteoforigin:,,,/Html/h1.html"); } 
} 

private Uri GetUri(string ItemName) 
{ 
    if (string.IsNullOrEmpty(ItemName)) return null; 

    return new Uri(@"pack://siteoforigin:,,,/Html/" + ItemName + ".html"); 
} 

utilizar de esta manera:

<controls:SmartBrowser x:Name="wbData" 
         Grid.Row="0" 
         HtmlUri="{Binding HtmlUri}" 
         DefaultUri="{Binding DefaultUri}" /> 

SmartBrowser.xaml:

<Grid> 
    <WebBrowser Name="wbData" /> 
</Grid> 

de control de código subyacente:

public partial class SmartBrowser : UserControl 
{ 
    #region Constants 
    private const int Feature = 21; 
    private const int SetFeatureOnProcess = 0x00000002; 
    #endregion 

    #region Api 
    [DllImport("urlmon.dll")] 
    [PreserveSig] 
    [return: MarshalAs(UnmanagedType.Error)] 
    static extern int CoInternetSetFeatureEnabled(int featureEntry, [MarshalAs(UnmanagedType.U4)] int dwFlags, bool fEnable); 
    #endregion 

    #region Fields 
    private WebBrowser _wbData; 
    #endregion 

    #region Constructor 
    public SmartBrowser() 
    { 
     InitializeComponent(); 
    } 
    #endregion 

    #region Overrides 
    public override void OnApplyTemplate() 
    { 
     base.OnApplyTemplate(); 

     _wbData = (WebBrowser)FindElement("wbData"); 
     if (_wbData != null) 
      if (DefaultUri != null) 
       _wbData.Navigate(DefaultUri); 
    } 
    #endregion 

    #region Properties 
    #region DefaultUri 
    /// <summary> 
    /// Gets/Sets 
    /// </summary> 
    public static readonly DependencyProperty DefaultUriProperty = 
     DependencyProperty.Register("DefaultUri", typeof(Uri), typeof(SmartBrowser), 
      new PropertyMetadata(null, new PropertyChangedCallback(OnDefaultUriChanged))); 

    public Uri DefaultUri 
    { 
     get { return (Uri)GetValue(DefaultUriProperty); } 
     set { SetValue(DefaultUriProperty, value); } 
    } 

    private static void OnDefaultUriChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 
    { 
     SmartBrowser sb = d as SmartBrowser; 

     if (e.NewValue == null) return; 
     if (sb._wbData == null) return; 

     Uri htmlUri = e.NewValue as Uri; 
     sb._wbData.Navigate(htmlUri); 
    } 
    #endregion 

    #region HtmlStream 
    /// <summary> 
    /// Gets/Sets 
    /// </summary> 
    public static readonly DependencyProperty HtmlStreamProperty = 
     DependencyProperty.Register("HtmlStream", typeof(Stream), typeof(SmartBrowser), 
      new PropertyMetadata(null, new PropertyChangedCallback(OnHtmlStreamChanged))); 

    public Stream HtmlStream 
    { 
     get { return (Stream)GetValue(HtmlStreamProperty); } 
     set { SetValue(HtmlStreamProperty, value); } 
    } 

    private static void OnHtmlStreamChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 
    { 
     SmartBrowser sb = d as SmartBrowser; 

     if (e.NewValue == null) return; 
     if (sb._wbData == null) return; 

     Stream htmlStream = e.NewValue as Stream; 
     sb.Navigate(htmlStream); 
    } 
    #endregion 

    #region HtmlString 
    /// <summary> 
    /// Gets/Sets 
    /// </summary> 
    public static readonly DependencyProperty HtmlStringProperty = 
     DependencyProperty.Register("HtmlString", typeof(string), typeof(SmartBrowser), 
      new PropertyMetadata(null, new PropertyChangedCallback(OnHtmlStringChanged))); 

    public string HtmlString 
    { 
     get { return (string)GetValue(HtmlStringProperty); } 
     set { SetValue(HtmlStringProperty, value); } 
    } 

    private static void OnHtmlStringChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 
    { 
     SmartBrowser sb = d as SmartBrowser; 

     if (e.NewValue == null) return; 
     if (sb._wbData == null) return; 

     string htmlString = e.NewValue as string; 

     sb.Navigate(htmlString); 
    } 
    #endregion 

    #region HtmlUri 
    /// <summary> 
    /// Gets/Sets 
    /// </summary> 
    public static readonly DependencyProperty HtmlUriProperty = 
     DependencyProperty.Register("HtmlUri", typeof(Uri), typeof(SmartBrowser), 
      new PropertyMetadata(null, new PropertyChangedCallback(OnHtmlUriChanged))); 

    public Uri HtmlUri 
    { 
     get { return (Uri)GetValue(HtmlUriProperty); } 
     set { SetValue(HtmlUriProperty, value); } 
    } 

    private static void OnHtmlUriChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 
    { 
     SmartBrowser sb = d as SmartBrowser; 

     if (e.NewValue == null) return; 
     if (sb._wbData == null) return; 

     Uri htmlUri = e.NewValue as Uri; 
     sb.Navigate(htmlUri); 
    } 
    #endregion 

    #region SoundEffects 
    /// <summary> 
    /// Gets/Sets 
    /// </summary> 
    public static readonly DependencyProperty SoundEffectsProperty = 
     DependencyProperty.Register("SoundEffects", typeof(bool), typeof(SmartBrowser), 
      new PropertyMetadata(false, new PropertyChangedCallback(OnSoundEffectsChanged))); 

    public bool SoundEffects 
    { 
     get { return (bool)GetValue(SoundEffectsProperty); } 
     set { SetValue(SoundEffectsProperty, value); } 
    } 

    private static void OnSoundEffectsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 
    { 
     SmartBrowser sb = d as SmartBrowser; 

     if (e.NewValue == null) return; 
     if (sb._wbData == null) return; 

     bool enable = (bool)e.NewValue; 

     sb.EnableSoundEffects(enable); 
    } 
    #endregion 
    #endregion 

    #region Methods 
    private void EnableSoundEffects(bool Enable) 
    { 
     try 
     { 
      CoInternetSetFeatureEnabled(Feature, SetFeatureOnProcess, !Enable); 
     } 
     catch { } 
    } 

    private void Navigate(Uri Html) 
    { 
     if (Html == null) return; 

     try 
     { 
      _wbData.Navigate(Html); 
     } 
     catch { } 
    } 

    private void Navigate(string Html) 
    { 
     if (string.IsNullOrEmpty(Html)) return; 

     try 
     { 
      _wbData.NavigateToString(Html); 
     } 
     catch { } 
    } 

    private void Navigate(Stream Html) 
    { 
     if (Html == null) return; 

     try 
     { 
      _wbData.NavigateToStream(Html); 
     } 
     catch { } 
    } 
    #endregion 

    #region Helpers 
    /// <summary> 
    /// Find an element in the visual tree 
    /// </summary> 
    /// <param name="name">Element name</param> 
    /// <returns>Element [object]</returns> 
    private object FindElement(string name) 
    { 
     try 
     { 
      if (this.Template != null) 
       return this.FindName(name); 
     } 
     catch { } 
     return null; 
    } 
    #endregion 
} 
2

Set "Acción de generación" del archivo a "Recurso incrustado" y luego usar esto:

webBrowserMain.NavigateToStream(System.Reflection.Assembly.GetEntryAssembly().GetManifestResourceStream("PsHandler.Resources.gnu.html")); 

Así es cómo se ve en el proyecto: http://i.stack.imgur.com/dGkpH.png

2

Es posible que desee utilizar el siguiente esquema en su lugar:

  1. Cambiar Acción de generación de su recurso para contenido.
  2. Establecer Copiar al Directorio de salida a Copiar si es más nuevo.
  3. Utilice el siguiente esquema URI:

    <WebBrowser Source="pack://siteoforigin:,,,/Resources/page1.html" /> 
    

A partir de .NET 4.5, esto funciona muy bien para mí.

+0

_Mejor_respuesta para .NET 4.5+. Las URL de paquete le permiten usar imágenes y otros recursos dentro del archivo .html. –

Cuestiones relacionadas