How can I access ResourceDictionary in wpf from C# code?

后端 未结 9 1535
[愿得一人]
[愿得一人] 2020-11-30 03:04

I have a DataTemplate defined in a xaml file that I want to access via C# code. Can anyone please tell me how can I access it? I added a new ResourceDicti

相关标签:
9条回答
  • 2020-11-30 03:33

    Since Application.Current was null in my case, I've ended up using this:

        var myResourceDictionary = new ResourceDictionary();
        myResourceDictionary.Source =
            new Uri("/DllName;component/Resources/MyResourceDictionary.xaml",
                    UriKind.RelativeOrAbsolute);  
    

    and then getting the specified key I needed by using myResourceDictionary["KeyName"] as TypeOfItem

    (source)

    0 讨论(0)
  • 2020-11-30 03:38

    You can access a resource dictionary you added to your project as follows:

    var rd = new ResourceDictionary();
    rd.Source = new Uri("ms-appx:///Dictionary1.xaml");
    

    Then you can access a resource stored in the resource dictionary like so:

    someObject.Property = rd["mytemplate"];
    

    NOTE:
    You will have to modify the URI to the resource dictionary according to the location you created it relative to the project's base directory.

    0 讨论(0)
  • 2020-11-30 03:38

    For the life of me, although I was able to load my resource dictionary via XAML, I wasn't able to load it via "code behind" (in C#).

    So I resorted to have a view loading it: (MyView.xaml)

      <UserControl.Resources>
        <ResourceDictionary>
          <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/My.Proj;component/My/Path/myResourceDictionary.xaml" />
          </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
      </UserControl.Resources>
    

    Then access it in my UT by instanciating that view and accessing it:

    new MyView().Resources.MergedDictionaries[0]

    Hacky, but works.

    0 讨论(0)
提交回复
热议问题