'How to bind DataTemplates to ContentPresenter
I have read some questions-answers explaining this topic (1,2,3) but i'm still missing something.
I have defined a `ResourceDictionary` with several `DataTemplate` for exmaple :
<ResourceDictionary
xmlns:wvm="clr-namespace:Octopus.Widgets.ViewModels;assembly=Octopus.Widgets"
xmlns:wuc="clr-namespace:Octopus.Widgets.Controls;assembly=Octopus.Widgets">
<DataTemplate DataType="{x:Type wvm:ClockViewModel}">
<wuc:Clock />
</DataTemplate>
</ResourceDictionary>
And merge it in the Application.Resources ResourceDictionary.MergedDictionaries section.
Now comes the part i don't understand.
How do I show a template in other control? I saw the use of <ContentPresenter Content="{Binding CurrentView}"/> but can't really understand it. Does the ViewModel of the container(parent) has a CurrentView property ? and what type it is then?
this is the parent-container control-view :
<Grid>
<!-- hard coded control - i want to change it -->
<Button>
<wuc:Clock VerticalAlignment="Center" HorizontalAlignment="Center">
<wuc:Clock.DataContext>
<wvm:ClockViewModel/>
</wuc:Clock.DataContext>
</wuc:Clock>
</Button>
<!-- another try -->
<!--<ContentControl>
<ContentControl.Style>
<Style TargetType="{x:Type ContentControl}">
<Setter Property="ContentTemplate" Value="{Binding WidgetTemplate}" />
</Style>
</ContentControl.Style>
</ContentControl>-->
</Grid>
Thanks
EDIT
My goal is to be able to switch widget based on key comming from DB.
Container control has a ViewModel with some properties not related to question. But maybe missing one that does and this is my question.
Solution 1:[1]
For the generations to come here is my solution:(thanks to @clemens for putting me on track)
In the container ViewModel i added a property to hold the selected widget type
public object Content
{
get { return content; }
set
{
content = value;
this.RaisePropertyChanged("Content");
}
}
and according to Widget i needed i initialized a new ViewModel (defined in DataTemplate)
And the xaml i used :
<ContentPresenter Content="{Binding Content}"/>
Simple enough....
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | gilad |
