2010-11-17 15 views
13

Supponiamo di avere una proprietà HTML (stringa). Posso legarlo a un controllo WebBrowser WPF? C'è la proprietà Source in cui ho bisogno di un URI, ma se ho una stringa HTML in memoria che voglio renderizzare, posso farlo? Sto usando MVVM, quindi penso che sia più difficile usare metodi come webBrowser1.NavigateToString() ecc? cos non conoscerò il nome del controllo?È possibile associare HTML a un controllo browser Web WPF?

risposta

42

Vedere la domanda this.

In sintesi, prima si crea una proprietà associata per browser web

public class BrowserBehavior 
{ 
    public static readonly DependencyProperty HtmlProperty = DependencyProperty.RegisterAttached(
      "Html", 
      typeof(string), 
      typeof(BrowserBehavior), 
      new FrameworkPropertyMetadata(OnHtmlChanged)); 

    [AttachedPropertyBrowsableForType(typeof(WebBrowser))] 
    public static string GetHtml(WebBrowser d) 
    { 
     return (string)d.GetValue(HtmlProperty); 
    } 

    public static void SetHtml(WebBrowser d, string value) 
    { 
     d.SetValue(HtmlProperty, value); 
    } 

    static void OnHtmlChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) 
    { 
     WebBrowser webBrowser = dependencyObject as WebBrowser; 
     if (webBrowser != null) 
      webBrowser.NavigateToString(e.NewValue as string ?? " "); 
    } 
} 

E poi è possibile associare alla stringa di html e NavigateToString saranno chiamati ogni volta che la stringa di codice HTML cambia

<WebBrowser local:BrowserBehavior.Html="{Binding MyHtmlString}" /> 
+0

Questo è un bel trucco. Tuttavia, quando si tenta di incorporare un WebBrowser all'interno di un DataTemplate (ad esempio, quando si tenta l'elemento di una casella combinata) non sembra funzionare (per qualche motivo, OnHtmlChanged viene generato due volte, la seconda volta con null). – Tomer

+0

@tomer Ho avuto lo stesso problema, quindi ho appena cambiato e.NewValue come stringa su e.NewValue come stringa ?? " ". Ho modificato il codice per riflettere questo. –

Problemi correlati