c# - WPF bind boolean value to image display -
i trying display either red or green icon in several grids based upon value of boolean variable set machine states(off/on). converter best way accomplish this? having troubles binding variables image field on grid. cannot seem fire off booltoimageconverter class? thank guidance.
using booltoimageconverter. when using code, check resources , paths them. (images, converters, models (for models , converters check namespaces)).
demo: in demo, changed property name flag, , booltoimageconverter read property , created bitmapimage.
app.xaml:
<application x:class="wpfapplication1.app" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:conv="clr-namespace:converters" startupuri="mainwindow.xaml"> <application.resources> <resourcedictionary> <conv:booltoimageconverter x:key="booltoimageconv" /> </resourcedictionary> </application.resources>
mainwindow.xaml:
<grid x:name="layoutroot"> <!--image demonstration, binding--> <image x:name="targetimageblock" source="{binding flag, converter={staticresource booltoimageconv}}" verticalalignment="top" horizontalalignment="left" height="100" width="100"/> <!--button changing property in view model--> <button content="change" horizontalalignment="right" verticalalignment="top" margin="15" padding="15" click="button_click"/> </grid>
mainwindow.cs:
public partial class mainwindow : window { // create view model somemodel model = new somemodel(); public mainwindow() { initializecomponent(); loaded += mainwindow_loaded; } void mainwindow_loaded(object sender, routedeventargs e) { loaded -= mainwindow_loaded; // set context this.datacontext = model; } private void button_click(object sender, routedeventargs e) { // change property in view model (not image) if (model.flag) model.flag = false; else model.flag = true; } }
somemodel.cs:
public class somemodel : inotifypropertychanged { public event propertychangedeventhandler propertychanged; private bool _flag = false; /// <summary> /// flag bool value. /// </summary> public bool flag { { return _flag; } set { if (_flag != value) { _flag = value; notify(); } } } private void notify([callermembername] string name = "") { var h = propertychanged; if (h != null) h(this, new propertychangedeventargs(name)); } }
booltoimageconverter:
namespace converters { public class booltoimageconverter : ivalueconverter { public object convert(object value, type targettype, object parameter, system.globalization.cultureinfo culture) { bool val = (bool)value; if (val) { return new bitmapimage(new uri("/images/like.png", urikind.relativeorabsolute)); } else { return new bitmapimage(new uri("/images/favs.png", urikind.relativeorabsolute)); } } public object convertback(object value, type targettype, object parameter, system.globalization.cultureinfo culture) { throw new notimplementedexception(); } } }
Comments
Post a Comment