Question

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?
Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top