Skip to content

Elements which are demand created and shared across Pages in WPF

February 5, 2007

Imagine that you have several pages where you may want to instantiate the same object (or a small tree of objects).  You want to make sure that you only create a new object the first time…and you want to do it via XAML.

This sample <ProxyElement /> may help you do this…



using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Controls;
using System.ComponentModel;
using System.Windows.Media;
using System.Windows;

namespace Microsoft.Samples.RobRelyea.WpfUtilities


public class ProxyElement : Border, ISupportInitialize


public ProxyElement()



private string _ProxyName;

public string ProxyName


get { return _ProxyName; }

set { _ProxyName = value; }


#region ISupportInitialize Members

void ISupportInitialize.BeginInit()


this.Loaded += new RoutedEventHandler(ProxyElement_Loaded);


void ISupportInitialize.EndInit()



UIElement element = null;

void ProxyElement_Loaded(object sender, RoutedEventArgs e)


string appPropertyName = "SavedElement_" + ProxyName;

Application app = Application.Current;

if (app.Properties[appPropertyName] == null)


element = this.FindResource(ProxyName) as UIElement;

app.Properties[appPropertyName] = element;




element = app.Properties[appPropertyName] as UIElement;

if (element != null)


ProxyElement proxy = LogicalTreeHelper.GetParent(element) as ProxyElement;

proxy.Child = null;



if (element != null)


this.Child = element;

element.SetValue(FrameworkElement.NameProperty, ProxyName);

this.RegisterName(ProxyName, element); //is this necessary with the Name being set above while it is in the tree?






Put the content you want reused in App.xaml:


<Ellipse x:Key="sharedEllipse"


Stroke="Orange" />


Put a reference in each xaml file you’d like to include it in:

<StackPanel xmlns:rr="clr-namespace:…" >

<rr:ProxyElement ProxyName="sharedEllipse" Margin="10,30,100,200"/>



From → WPF

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: