Search code examples
c#wpfcontentpresenteruielement

Is it appropriate to cast ContentPresenter.Content to UIElement?


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?

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.