In XAML I do it like this:
<Button Style="{StaticResource NavigationBackButtonNormalStyle}" />
How do I do the same thing in code-behind?
To add a Resource Dictionary into your WPF application, right click the WPF project > add a Resource Dictionary. Now apply the resource "myAnotherBackgroundColor" to button background and observe the changes.
The page-level Resources object has the ability to find local, app-level, static, and theme resources. This means you simply do this:
foo2.Style = this.Resources["NavigationBackButtonNormalStyle"] as Style;
Best of luck!
During design-time, it seems that trying to resolve a "system resource" using Resources[key]
will fail to find the resource and will return null
. For example, to get the base Style
for a TextBox
using Resources[typeof(TextBox)]
will return null
.
Instead, use TryFindResource(key)
since this will first try Resources[key]
and then will otherwise try searching through the "system resources" and will return what you're looking for (as per MSDN and Reference Source).
In other words, try this instead:
var style = Application.Current.TryFindResource(key) as Style;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With