How can I get a named resource from ControlTemplate in a code-behind file (*.xaml.cs)? TryFindResource returns null. Template property of the control is also null. What else should I try? Thanks.
+1
A:
Are you using custom control?
If yes, you can override OnApplyTemplate method in custom control and can use Template.Find("name of resource")
then expose it as a property from the control.
if No, then use custom control.
Hope it helps!
viky
2010-09-25 16:57:48
Do you control that is derived from Control class? If so, yes it is derived from it. Thank you for OnApplyTemplate clue. Although Template doesn't contain Find method, I still able to access resources via Tempate.Resources["name of resource"]. That's fine. BUT. My problem is that I need to access it in private static void OnCategoryNameChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) methodd which is called whenever someone changes Category dependency property. Depending on category I should change the control's background.
Bashir Magomedov
2010-09-26 11:57:01
This method is called even when I'm setting values of Category property first time (in XAML markup), but by that time OnApplyTemplate hasn't been fired, i.e. template hasn't been probably applied yet, so Template property returns null :(. Is there any workaround here? I think I'm kind of missing a point here...
Bashir Magomedov
2010-09-26 12:00:27
@Bashir Magomedov: you can derive custom control from control class or any derived class. In your case, you have to do the same thing that you are doing in OnCategoryNameChanged handler, from OnApplyTemplate as well. In OnCategoryNameChanged handler, check if Template is applied otherwise do the same stuff in OnApplyTemplate. You may need to use some private variables in your class to keep track on this.
viky
2010-09-27 04:59:02
Thanks! That might be a solution, but I think that I really missed such feature as Triggers. I replaced my OnCategoreNameChanged handler with bunch of triggers in XAML! Any way thank you!
Bashir Magomedov
2010-09-27 05:29:51