Shiny Silverlights

...Another Silverlight MVP blog

oob

...now browsing by category

 

Different DataTemplate for OOB mode aka loading XAML from string

Monday, November 22nd, 2010

WebBrowser control is an awesome way to display rich HTML content, sadly we can only use it with OOB applications. I decided that although the preferred way of using my app is to install it on the desktop (and see the WebBrowser control), I still want to show something, maybe less fancy data when the app is running in the browser. So I created two DataTemplates one for OOB and one for the browser.

In my UserControl XAML I simply have a named ItemsControl:

image

And in C# I load the DataTemplate for this ItemsControl based on the situation:

image

Loading XAML from String

Loading XAML from a string is really easy, you only need to use one method – XamlReader.Load(xamlString); and cast it to whatever element you need to use it as. The important part here is that you need to reference all the same namespaces you reference in your other XAML files, cause this XAML doesn’t know anything about those.

image

This code example shows the DataTemplate that I use when the app is running on the browser, the other template has slightly different layout and uses the WebBrowser control. Of course you could also load the template from a file, have one default template defined in XAML and only override it when running out of browser – then you’d also see something design time :).

webbrowser control binding

Friday, October 1st, 2010

I have to admit the WebBrowser control in Silverlight 4 isn’t quite what I expected and needed but at least we have the possibility to display HTML content in Silverlight apps when running out of browser. The implementations has one limitation though – the browser source can’t be databound. It either has to be directing to an URL or you can load HTML by calling NavigateToString method.

Since I wanted to use the web browser control in a datatemplate, the only reasonable way was to create an attached property to WebBrowser control that calls NavigateToString when it changes.

What are attached properties?

In short using attached properties is a great way to extend the functionality of existing classes without the need to subclass them. An attachable property may be very specific allowing it to be attached to only certain classes like WebBrowser for example or a bit more general like Grid.Row and Grid.Column properties that can be attached to any UIElement.

Read more from MSDN

Bindable WebBrowser Control

image

To use this attachable property, I add BindableWebBrowser.Html to WebBrowser Xaml local:BindableWebBrowser.Html=”{Binding Content}”

image