Take the 2-minute tour ×

I've got a very simple app.xaml.cs that, when the app starts up, creates a new PrimeWindow, and makes it accessible to the outside.

public partial class App : Application
    public static PrimeWindow AppPrimeWindow { get; set; }

    private void Application_Startup(object sender, StartupEventArgs e)
        AppPrimeWindow = new PrimeWindow();

The xaml for PrimeWindow looks like this:

<Window x:Class="WpfApplication1.PrimeWindow"
    Title="Window1" Height="500" Width="500"
    <DockPanel Name="dockPanel1" VerticalAlignment="Top">
        <MyControls:ContentArea x:Name="MyContentArea" />

Being a complete WPF novice, I'm doubtless messing several things up, but the question of the moment is this: how do I reference the content area in code elsewhere? I can easily get ahold of the DockPanel, via something like

DockPanel x = App.AppPrimeWindow.dockPanel1;

But digging any deeper doesn't seem easy to do. I can get a UIElementCollection of the DockPanel's children, and I can get individual children by an integer index, but, from a maintainability standpoint, that's clearly not the way to do this.

share|improve this question

3 Answers 3

up vote 1 down vote accepted

If you need to reference the children, passing the UIElementCollection around would do it. If you just wanted to access MyContentArea, there's nothing stopping you from doing the following:

MyControls.ContentArea = App.AppPrimeWindow.myContentArea;

If you need to dynamically see if theres a ContentArea within your DockPanel, the following would work:

DockPanel dock = App.AppPrimeWindow.dockPanel1;

for (int i = 0; i < dock.Children.Count; i++)
  if (dock.Children[i] is ContentArea) // Checking the type
    ContentArea ca = (ContentArea)dock.Children[i];
    // logic here
    // return;/break; if you're only processing a single ContentArea
share|improve this answer
All the answers are good for different reasons; however, this one highlights the easiest way to do this, and also explained something else to me at the same time. So: acceptance. –  Beska Dec 11 '09 at 22:12

Very simply,

ContentArea contentArea = dockpanel1.FindName("MyContentArea") as ContentArea;
share|improve this answer
This is essentially what I was trying, and figuring I had to do, but didn't realize that FindName was what I was looking for...thanks! –  Beska Dec 11 '09 at 22:13
<DockPanel Name="dockPanel1" x:FieldModifier="Public" VerticalAlignment="Top">

This will make the dockPanel1 field public, so it will be accessible from other classes

Note that it's not very good practice as it breaks encapsulation... You could also expose the DockPanel as a public property defined in your code-behind

share|improve this answer
Thanks! Now I just need to figure out if I really want to break encapsulation here, or if there's a better way to do what I'm trying to do (probably.) –  Beska Dec 11 '09 at 22:13

Your Answer


