Accessing ResourceDictionary from WPF UserControl

前端 未结 4 752
孤城傲影
孤城傲影 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");
    

提交回复
热议问题