When I attempt to specify multiple DataTemplates for use by a ContentControl so that the correct one (based on Type) is used, I end up with Content that is simply the Content's ToString() value.
<ContentControl DataContext="{Binding MyTreeRootViewModels}" Content="{Binding /, Path=CurrentlySelectedTreeViewModel}"> <ContentControl.Resources> <DataTemplate DataType="x:Type vm:TypeAViewModel"> <StackPanel> <local:TypeAUserControl /> </StackPanel> </DataTemplate> <DataTemplate DataType="x:Type vm:TypeBViewModel"> <StackPanel> <local:TypeBUserControl /> </StackPanel> </DataTemplate> </ContentControl.Resources> </ContentControl>
In the example above I would see "MyApp.ViewModel.TypeAViewModel" displayed when a tree node of TypeAViewModel is returned by CurrentlySelectedTreeViewModel. I expect to see my TypeAViewModelUserControl.
I've tried putting a single <TextBlock Text="TESTING"/> element in one of my DataTemplates just to see if the problem was related to my user controls. Same result.
Any ideas what I am doing wrong?
(By the way, the CurrentlySelectedTreeViewModel is a property that returns the currently selected node in my treeview. It seems to work just fine - as I select nodes in the tree, the correct type name for the node appears ContentControl).
ContentControl is a base class for controls that contain other elements and have a Content -property (for example, Button ). ContentPresenter is used inside control templates to display content.
According to Microsofts App Studio the DataTemplates should live in a DataTemplates Subdirectory under the Views Directory.
A ControlTemplate will generally only contain TemplateBinding expressions, binding back to the properties on the control itself, while a DataTemplate will contain standard Binding expressions, binding to the properties of its DataContext (the business/domain object or view model).
A data template can contain elements that are each bound to a data property along with additional markup that describes layout, color and other appearance. DataTemplate is, basically, used to specify the appearance of data displayed by a control not the appearance of the control itself.
The x:Type
bit should be between curly braces {}
:
<DataTemplate DataType="{x:Type vm:TypeAViewModel}">
x:Type
is a MarkupExtension, which requires {}
to indicate to the XAML compiler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With