Josh Smith MVVM Demo

In MainWindow we have:

<HeaderedContentControl Content="{Binding Path=Workspaces}" ContentTemplate="{StaticResource WorkspacesTemplate}" Header="Workspaces" Style="{StaticResource MainHCCStyle}" /> 

In the resources :

  <DataTemplate x:Key="WorkspacesTemplate"> <TabControl IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding}" ItemTemplate="{StaticResource ClosableTabItemTemplate}" Margin="4" /> </DataTemplate> 

And the article says:

The dialed DataTemplate does not have the x: Key value assigned to it, but it does have the DataType property specified by the class instance. If WPF tries to display one of your ViewModel objects, it will check to see if the resource system has a typed DataTemplate in the area whose DataType matches (or base class) the type of your ViewModel . If it finds one, it uses this template for the ViewModel object referenced by the contents property of the tab.

My question is :

How does a template know that a type is a collection of workspaces (WorkspaceViewModel)?

+6
source share
2 answers

The code you posted is not necessary. In your example, you strictly specified the content template: you explicitly used {StaticResource WorkspacesTemplate} , and therefore the resource with the key "WorkspacesTemplate viewed.

Since you explicitly defined the template, it does not matter what the assigned type is: it will try to display any object in your Content using the template that you installed, with varying degrees of success, if you use a type that does not match!

In the alternative method that you mentioned - using the "typed DataTemplate", you must declare your datatemplate using <DataTemplate DataType="{x:Type l:WorkSpace}" /> . Note that there is no x:Key (and also I assumed that you have a namespace l mapped to your local code). What happens here is that WPF automatically sets your resource key to DataType (it’s important to note: the resource key does not have to be a string!).

Then, when you declare your HeaderedContentControl , you can leave the ContentTemplate setting. At run time, when the control is displayed, WPF checks the type of the Content object and finds that it is WorkSpace , and then it searches for the resource with x:Key="{x:Type l:WorkSpace}" - which will match your typed template.

This is a useful way to create consistent representations of data throughout the application, since a typed DataTemplate will be automatically used by any content presentation control in your application.

+4
source

WPF doesn’t really care about a particular type, it just needs to be some IEnumerable of something, WPF uses a type descriptor to find out what ui is bound to.

+4
source

Source: https://habr.com/ru/post/946752/


All Articles