Accessing ResourceDictionary from WPF UserControl

前端 未结 4 750
孤城傲影
孤城傲影 2021-01-18 05:55

I\'m trying to access a resource dictionary in a UserControl code-behind via C# and I\'m having little success.

Merged Dictionary:



        
相关标签:
4条回答
  • 2021-01-18 06:37

    To access one of your UserControl's XAML resources in your codebehind, all you need to do is access the Resources property of the UserControl. Something like this:

    BitmapImage myImage = (BitmapImage)this.Resources["imageDefault"];
    

    Though, the preferred method is to use FindResource(), which will search the entire logical tree for a match to the key, rather than just the object it is called on.

    BitmapImage myImage = (BitmapImage)this.FindResource("imageDefault");
    
    0 讨论(0)
  • 2021-01-18 06:39

    Try to remove the forward slash infront of your location. The only time you should use /Resources is if you have to go up a library first. like ../Resources

    <UserControl.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
               <ResourceDictionary Source="Resources/BiometricDictionary.xaml" />                
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </UserControl.Resources>
    

    Hope this helps you.

    0 讨论(0)
  • 2021-01-18 06:49

    So, you have a ResourceDictionary defined in a UserControl's assembly, and would like to access it from that UserControl's code-behind?

    You should be able to. However, if the code you listed is in the constructor, you may not have access to the resource dictionary (might not be loaded yet). Try adding that same code to your UserControl's "loaded" event, and see if that works. If you're simply trying to access a resource, such as a style or template, using the "FindResource" or "TryFindResource" functions directly from your class should work as well (i.e. you don't need to have an object of type "ResourceDictionary").

    Hope that helps!

    0 讨论(0)
  • 2021-01-18 06:52

    d'Oh...after compiling to the local bin so that references are relative, I implemented the pack URI solution found here: ResourceDictionary in a separate assembly and then FindResource(x:key value here).

    @PeterAllenWeb, @Pwninstein, thanks for your quick responses and getting me thinking again.

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