There are ways to do what you're asking here, as explained in this CodeProject Article:
Creating WPF Data Templates in Code: The Right Way
However, most of the time you really don't need that for daily operations.
If you're working with WPF, you really need to leave behind the traditional approach from other frameworks and embrace The WPF Mentality.
HTML (4, 5 or whatever) looks like a ridiculous joke when compared to the WPF implementation of XAML, therefore all the horrendous hacks you might be used to in HTML are completely unneeded in WPF, because the latter has a lot of built-in features that help you implement advanced UI capabilities in a really clean way.
WPF is heavily based on DataBinding and promotes a clear and well-defined separation between UI and Data.
For example, this would be what you would do to when you want to "show different pieces of UI" depending on the Data, by using a WPF feature called DataTemplates:
XAML:
<Window x:Class="MyWindow"
...
xmlns:local="clr-namespace:MyNamespace">
<Window.Resources>
<DataTemplate DataType="{x:Type local:Person}">
<!-- this is the UI that will be used for Person -->
<TextBox Text="{Binding LastName}"/>
</DataTemplate>
<DataTemplate DataType="{x:Type local:Product}">
<!-- this is the UI that will be used for Product -->
<Grid Background="Red">
<TextBox Text="{Binding ProductName}"/>
</Grid>
</DataTemplate>
</Window.Resources>
<Grid>
<!-- the UI defined above will be placed here, inside the ContentPresenter -->
<ContentPresenter Content="{Binding Data}"/>
</Grid>
</Window>
Code Behind:
public class MyWindow
{
public MyWindow()
{
InitializeComponent();
DataContext = new MyViewModel();
}
}
ViewModel:
public class MyViewModel
{
public DataObjectBase Data {get;set;} //INotifyPropertyChanged is required
}
Data Model:
public class DataObjectBase
{
//.. Whatever members you want to have in the base class for entities.
}
public class Person: DataObjectBase
{
public string LastName {get;set;}
}
public class Product: DataObjectBase
{
public string ProductName {get;set;}
}
Notice how I'm talking about my Data
and Business Objects
rather than worried about any hacks to manipulate the UI.
Also notice how defining the DataTemplates in XAML files that will get compiled by Visual Studio gives me compile-time checking of my XAML as opposed to putting it together in a string
in procedural code, which of course doesn't have any kind of consistency checks.
I strongly suggest you read up on Rachel's answer (linked above) and related blog posts.
WPF Rocks