views:

399

answers:

1

Hi,

I have a requirement that based on the User who logged in to my application I need to show a different view. How can I achieve this using datatemplates?

Thanks, Jithu

A: 

Say you have Resource Dictionaries in the root of your WPF project like these for each User group/type:

  • UserOneResources.xaml
  • UserTwoResources.xaml
  • ...

Which contains DataTemplates:

<!-- UserOneResources.xaml -->
<DataTemplate DataType="{x:Type s:String}">
    <TextBlock Text="{Binding .}" />
</DataTemplate>

<!-- UserTwoResources.xaml -->
<DataTemplate DataType="{x:Type s:String}">
    <TextBox Text="{Binding .}" />
</DataTemplate>

Then in the constructor of your App.xaml.cs you can select appropriate resource dictionary for the current user type like the following:

public App()
{
    string resourceDictionaryToUse;

    if (user.Type = UserType.One)
    {
        resourceDictionaryToUse = "UserOneResources.xaml";
    }
    else
    {
        resourceDictionaryToUse = "UserTwoResources.xaml";
    }

    var rd = new ResourceDictionary() { Source = new Uri("pack://application:,,,/" + resourceDictionaryToUse) };

    this.Resources.MergedDictionaries.Add(rd);
}

Hope this helps.

huseyint