2

I'm new in WPF, following MVVM pattern. trying to create dll, I have defined some resource strings in resourcedictionary, able to access it in xaml file but i need to access it in viewmodel. searched on net and found that there is one method TryFindResource() but this method is in application context, how can i use it in viewmode?

Thanks

user3106005
  • 179
  • 2
  • 18
  • 2
    Actually, trying to access WPF resource strings from the ViewModel usually is considered bad practice in MVVM. Normally, you should avoid to use any WPF functionality in the ViewModel. Therefore, it might be better to define the strings in the ViewModel and access the ViewModel's strings from your XAML (e.g. using `Binding` or `x:Static`). –  Jun 11 '14 at 05:25

1 Answers1

1

Hi you can have a static class like this below, this static class will have the reference of your resourceDIctionary, through this you can access the resources in the resource dictionary from your viewmodel.

internal static class SharedResourceDictionary
    {
        internal static ResourceDictionary SharedDictionary
        {
            get
            {
                if (_sharedDictionary == null)
                {
                    try
                    {
                        System.Uri resourceLocater1 = new System.Uri(
                                                        string.Format("/{0};component/YourResourceDictionary.xaml",
                                                        "YourProject"), System.UriKind.Relative);
                        ResourceDictionary resourceDictionary = new ResourceDictionary
                        {
                            Source = resourceLocater1
                        };
                        _sharedDictionary = resourceDictionary; 
                    }
                    catch (Exception e)
                    {

                    }
                }

                return _sharedDictionary;
            }
        }
        private static ResourceDictionary _sharedDictionary;
    }

You can get the resources from the viewmodel like this. Ex:

ResourceDictionary resourceDictionary = (ResourceDictionary)SharedResourceDictionary.SharedDictionary;

LinearGradientBrush brush = (LinearGradientBrush)resourceDictionary["ButtonNormalBackground"];
Sivasubramanian
  • 905
  • 7
  • 21