Thursday 15 January 2015

c# - Is it appropriate to cast ContentPresenter.Content to UIElement? -


Is there a situation where ContentPresenter is the content of UIElement ? Given that the field has been declared as an object instead of UIElement , it seems that it will happen, however, I can not think of any situation where it is, or even That it is also valid.

  ContentPresenter presenter = GetTemplateChild (PART_Presenter) as ContentPresenter; UIElement myElement = (UIElement) presenter. Material; MyElement.SomeUIMethod (); // Possible invalid operation exceptions?  

I do this all the time - and complete MVVM method non- UIElement Content, here is an example:

Create a class that is not derived from the UIElement , I will call MyViewModelClass in this example.

Create a window and add this code

  public partial squares window 1: window {public window 1 () {DataContext = new MyViewModelClass (); InitializeComponent (); }}  

and add some content controls to XAML:

  & lt; Button content = "{binding}" />  

Now you have a ContentPresenter (inside the button control template) with MyViewModelClass as the content.

Another (probably more common) example, for example, each ListBoxItem has a ContentPresenter which is in the list, whichever is it < Set the code> ItemControl ItemSource .


No comments:

Post a Comment