WPF Datatemplate with same viewmodel

Simon Ong 21 Reputation points

Please check below Xaml code

        <DataTemplate  DataType="{x:Type local:MainViewModel}">  
        <DataTemplate  DataType="{x:Type local:MainViewModel}">  

<ContentControl x:Name="Display" Content="{Binding CurrentViemModel}"/>

Error :The key is already defined in this scope

The View1_1_Usr and View_2_Usr need the same viewmodel. if added with different Key, problem will be able to go away.

How can i switch View in ContentControl by loading MainViewModel?

A language based on Extensible Markup Language (XML) that enables developers to specify a hierarchy of objects with a set of properties and logic.
790 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Hui Liu-MSFT 47,336 Reputation points Microsoft Vendor

    You could try to refer to the code below.

            <local:ViewModel x:Key="SharedViewModel" />  

    MainWindow.xaml and ViewModel:


      DataContext="{StaticResource SharedViewModel}">  
        <TextBlock Text="{Binding Name}" Width="100" Height="50" Background="LightPink"  Margin="50"/>  
        <Line x:Name="lin1" Stroke="Gray" StrokeThickness="2" X1="30" X2="30" Y1="20" Y2="40"/>  
        <Line x:Name="lin2" Stroke="Blue" StrokeThickness="2" X1="40" X2="40" Y1="20" Y2="40"/>  
        <Line x:Name="lin3" Stroke="Red" StrokeThickness="2" X1="50" X2="50" Y1="20" Y2="40"/>  


    DataContext="{StaticResource SharedViewModel}" >  
        <Button Content="{Binding Address}" Width="100" Height="50" Background="AliceBlue"  Margin="70"/>  
        <Line x:Name="lin1" Stroke="Gray" StrokeThickness="2" X1="30" X2="130" Y1="40" Y2="40"/>  
        <Line x:Name="lin2" Stroke="Blue" StrokeThickness="2" X1="30" X2="120" Y1="50" Y2="50"/>  
        <Line x:Name="lin3" Stroke="Red" StrokeThickness="2" X1="30" X2="120" Y1="60" Y2="60"/>  

    The result:


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.