Navigation |
WPF VisualHostIn WPF, the Visual class is the base class for everything that ends up on the screen. In this respect, it is sort-of comparable to an HWND in classic Windows. Most of the time you end up working with things that are derived from Visual, like Controls, but every now and then you end up with a Visual by itself. For example, when working with FlowDocuments, if you extract a page, the page is returned as a Visual. The problem is that, unless you are doing your own rendering, there is not a whole lot you can do with a Visual. You can't, for example, put it in a layout or really interact with it in any way. You can render it out to a bitmap, and then put that bitmap into an Image control, but then you just a picture of your content-you can't, for example, select text it contains. The simple solution is to put the Visual into some sort of Visual Host control. Unfortunately, Microsoft didn't provide one. However, it is trivial to create one. The following code is for a VisualHost control that holds a single Visual. It would be very easy to make it hold multiple Visuals, but then there would have to be some logic to deal with presenting them.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Media;
namespace WPFInAction
{
class VisualHost : FrameworkElement
{
VisualCollection visuals;
public VisualHost()
{
visuals = new VisualCollection(this);
}
public Visual HeldVisual
{
get {return (visuals.Count > 0) ? visuals[0] : null;}
set
{
visuals.Clear();
visuals.Add(value);
}
}
protected override int VisualChildrenCount
{
get { return visuals.Count; }
}
protected override Visual GetVisualChild(int index)
{
return visuals[index];
}
}
}
By the way, the reason for using a collection to hold a single item is that the VisualCollection handles a lot of the underlying support for holding onto Visuals for us. Otherwise, we would have to do some work to make sure our parent knew about our child appropriately (which is not particularly a big deal, but this way we don't have to bother). Trackback URL for this post:http://www.exotribe.com/trackback/54 |
Recent blog posts
User login |