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

后端 未结 9 1580
[愿得一人]
[愿得一人] 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:31

    If you're getting the resources within the same project, try this:

    yourControl.Style = FindResource("YourResourceKey") as Style;
    

    Otherwise, try this:

    ResourceDictionary res = (ResourceDictionary)Application.LoadComponent(new Uri("/ProjectName;component/FolderName/ResourceDictionaryName.xaml", UriKind.Relative)); 
    yourControl.Style = (Style)res["YourResourceKey"];
    

提交回复
热议问题