6

I have a ContentControl whose content is determined by a DataTemplateSelector based on property Workspace. But when the data template is changed, I must do some calculations based on the initial size of ContentControl and the whole Window, so I want to know when it is Loaded.

<ContentControl Content="{Binding Path=Workspace}" ContentTemplateSelector="{StaticResource workspaceTemplateSelector}" />

ResourceDictionary:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
                    xmlns:vw="clr-namespace:Capgemini.Sag.KeyEm.View">

    <DataTemplate x:Key="keyboardTemplate"  >
        <vw:Keyboard/>
    </DataTemplate>

    <DataTemplate x:Key="welcomeTemplate">
        <vw:Welcome/>
    </DataTemplate>

    <vw:WorkspaceTemplateSelector            
        KeyboardTemplate="{StaticResource keyboardTemplate}"             
        WelcomeTemplate="{StaticResource welcomeTemplate}"        
        x:Key="workspaceTemplateSelector"/>
</ResourceDictionary>

DataTemplateSelector:

using Capgemini.Sag.KeyEm.ViewModel.Interfaces;

namespace Capgemini.Sag.KeyEm.View
{
    using System.Windows;
    using System.Windows.Controls;

    class WorkspaceTemplateSelector : DataTemplateSelector
    {
        public DataTemplate WelcomeTemplate { get; set; }
        public DataTemplate KeyboardTemplate { get; set; }

        public override DataTemplate SelectTemplate(object item, DependencyObject container)
        {
            if (item is IWelcomeViewModel)
                return WelcomeTemplate;
            if (item is IKeyboardViewModel)
                return KeyboardTemplate;
            return null;
        }
    }
}
magol
  • 6,135
  • 17
  • 65
  • 120
  • The proper way to handle this is to answer your own question and then, a couple days later, select it as the correct answer. –  Jan 25 '11 at 14:03

1 Answers1

1

One thing you can do is wrap your datatemplate content inside a container and listen to the loaded event

<DataTemplate x:Key="keyboardTemplate">
        <Grid Loaded="Grid_Loaded">
            <vw:Welcome/>
        </Grid>
    </DataTemplate>

the loaded event will be raised when the templates are switched.Hope this will help.

biju
  • 17,554
  • 10
  • 59
  • 95
  • Grid_Loaded have to be in the code-behind for the ResourceDictionary. But the calculations are in the Window that use the ResourceDictionary. How do I solve that? – magol Dec 10 '10 at 11:54
  • check if this helps http://stackoverflow.com/questions/92100/is-it-possible-to-set-code-behind-a-resource-dictionary-in-wpf-for-event-handling – biju Dec 10 '10 at 12:54
  • I now how to add a code-behind to the ResourceDictionary. But how do I communicate width the parent window? – magol Dec 10 '10 at 13:02