1

Are there any situations where the content of a ContentPresenter will be some object other than a UIElement? Given that the field is declared as object rather than a UIElement, it seems possible that there would be. However, I cannot think of any situations where it would be, or even if it would be valid.

ContentPresenter presenter = GetTemplateChild(PART_Presenter) as ContentPresenter;
UIElement myElement = (UIElement)presenter.Content;
myElement.SomeUIMethod(); // possible InvalidOperationException?
Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
jeffora
  • 4,009
  • 2
  • 25
  • 38
  • You will get an InvalidCastException in the 2nd line, not and InvalidOperationException on the third – Nir Dec 01 '09 at 09:36

2 Answers2

6

I do it all the time - and the entire MVVM method is built on non-UIElement content, here is an example:

Create a class that isn't derived from UIElement, I'll call is MyViewModelClass in this example.

Create a Window and add this code

public partial class Window1 : Window
{
    public Window1()
    {
        DataContext = new MyViewModelClass();
        InitializeComponent();
    } 
}

And add some content control to the XAML:

<Button Content="{Binding}"/>

Now you have a ContentPresenter (inside the Button control template) with MyViewModelClass as the Content.

Another (maybe more common) example is ItemControl - let's take a ListBox for example, each ListBoxItem has a ContentPresenter that has whatever was in the list set to ItemsSource.

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
Nir
  • 29,306
  • 10
  • 67
  • 103
4

Here's the most basic example I can think of

<Label Content="My Label" />

Now the content property is a string which doesn't derive from UIElement. So the short answer is yes, it's not only possible, it's likely to happen.

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
Bryan Anderson
  • 15,969
  • 8
  • 68
  • 83