Thursday, February 24, 2011

Programmatically Changing the XAML of a WPF Control


Despite many years as a Windows Forms developer, I am a beginner at writing software in Windows Presentation Foundation (WPF).  Most project requests I receive are for thin client web-based solutions.  I have not had a request for a desktop application that really required the advanced visual interactivity of WPF. That combined with the limited ability to use the Windows Forms controls that I know so well has kept me out of WPF.

I am now prototyping my first WPF application and feeling appropriately lost as I try to do things that I know that WPF can do but I have no inkling of how to accomplish.  I actually enjoy learning new technologies so I am not complaining, but I am.  You know what I mean.

I have a StackPanel as the content of a tab control panel at the right side of my main page.  That StackPanel will host of contents of the appropriate UserControl StackPanel based on which option is selected on the main page.  This allows the tab panel to change dynamically based on which left side-panel label is clicked.

The code-behind that worked to do this is below.  Before I get flamed, I realize that in a production application I would be using the MVVM or MVP pattern and I would not do it this way. But this is just a quick demo and I just want to illustrate the effect.

Project_Approval_Data is the name of the UserControl that has the content to appear in the tab control panel when the “Project Approval” TextBlock is clicked.  spContent is the name of the StackPanel has has the desired content; it is the same name in all the UserControls.

I am using Visual Studio 2010 Premium and .Net 4.0 Client Profile framework. I appreciate any comments showing a better way.

Yes, this particular project is being done in C# at the customer’s request.

Project_Approval_Data project_Approval_Data =
    new Project_Approval_Data();

string spXAML =
StackPanel spSource = (StackPanel)XamlReader.Parse(spXAML);
tabItem_DataTab.Content = spSource;


Hope that helps.

Joe Kunk
Microsoft MVP Visual Basic
Okemos MI USA 
February 24, 2011

No comments: