canvas - Dynamically switching between canvases wpf -
i have multiple canvas images of different types (image source, geometry, path) , wish show 1 depending on string binding.
whats best way this?
i'd reusable can place code inside user control , have many of these images around app , select 1 shown.
like so:
<canvasimage image="pie"/> <canvasimage image="dog"/>
would computationally expensive have them declared in user control view , use visibility bindings
pie canvas example:
<canvas> <data ="m24,98,07"> </canvas>
dog canvas example:
<canvas> <image source=""> <canvas>
this converter return image source directly, depending on value receives.
namespace testtreeview.views { public class stringtoimageconverter : ivalueconverter { public object convert(object value, type targettype, object parameter, cultureinfo culture) { string file = ""; string v = value string; switch (v) { case "pie": file = @".\path\to\your\pie.jpg"; break; case "dog": file = @".\path\to\your\dog.jpg"; break; default: return null; } return new bitmapimage(new uri(file, urikind.relativeorabsolute)); } public object convertback(object value, type targettype, object parameter, cultureinfo culture) { throw new notimplementedexception(); } } }
usage in xaml:
<window xmlns:local="clr-namespace:yournamespace.views" ...> <window.resources> <local:stringtoimageconverter x:key="stringtoimageconverter"/> </window.resources> <grid> <canvas> <image source="{binding yourstring, converter={staticresource stringtoimageconverter}}"/> </canvas> </grid> </window>
original answer
i think need use converter.
take converterparameter, string, tell binded value expected be, , return visiblity indicate if canvas should visible or not.
namespace yournamespace.views { public class stringtocanvasvisibilityconverter : ivalueconverter { public object convert(object value, type targettype, object parameter, cultureinfo culture) { string v = value string; string p = parameter string; return (v != null && p != null && v == p) ? visibility.visible : visibility.collapsed; } public object convertback(object value, type targettype, object parameter, cultureinfo culture) { throw new notimplementedexception(); } } }
usage in xaml:
<window xmlns:local="clr-namespace:yournamespace.views" ...> <window.resources> <local:stringtovisibilityconverter x:key="stringtovisibilityconverter"/> </window.resources> <grid> <canvas visibility="{binding yourstring, converter={staticresource stringtovisibilityconverter}, converterparameter=pie}"/> <canvas visibility="{binding yourstring, converter={staticresource stringtovisibilityconverter}, converterparameter=dog}"/> </grid> </window>
Comments
Post a Comment