wpf - IValueConverter to convert a resource referenced by StaticResource -
i looking use ivalueconverter value getting resources of application. noticed similar question asked few years ago here: how bind staticresource converter?.
however, updating source attribute object in resources didn't work me. particular case:
<textblock text="sampletext" foreground="{binding source={staticresource appthemecolor}, converter={staticresource themecolortobrushconverter}, converterparameter={staticresource applicationforegroundthemebrush}, mode=oneway}" />
the appthemecolor defined , set dynamically in code behind @ stage of app launch. logic in converter says use color provided unless app in highcontrast mode, in case uses brush supplied in converterparameter.
does know of pitfalls might running here? there no compile or run time errors. text doesn't appear , converter's convert doesn't seem getting called.
edit: asking how setting appthemecolor dynamically. added following one-liner here in app.xaml.cs's onactivatedasync:
application.current.resources[appthemecolorresourcekey] = (themeexists) ? branding.themecolor : bluethemecolor;
you can transform these staticresources "style" class
app , assign window.datacontext
.
i think best approach case.
if project uses mvvm pattern, create class using singleton pattern , use property viewmodel need style.
style class:
using system.componentmodel; using system.runtime.compilerservices; using system.windows.media; public class defaultstyleclass : inotifypropertychanged { private brush _appthemecolor; public brush appthemecolor { { return _appthemecolor; } set { if(value != _appthemecolor) { _appthemecolor = value; notifypropertychanged(); } } } public defaultstyleclass() { appthemecolor = brushes.red; } public event propertychangedeventhandler propertychanged; private void notifypropertychanged([callermembername] string propertyname = "") { var propertychanged = propertychanged; if (propertychanged != null) { propertychanged(this, new propertychangedeventargs(propertyname)); } } }
need assign datacontext of window
code:
public defaultstyleclass stylecontext; public mainwindow() { initializecomponent(); stylecontext = new defaultstyleclass(); datacontext = stylecontext; }
on xaml:
<textblock text="sampletext", foreground="{binding appthemecolor}, converter={staticresource themecolortobrushconverter}, converterparameter={staticresource applicationforegroundthemebrush}, mode=oneway}" />