'Powershell WPF checkbox binding
I have a MenuItem Checkbox in my main window as well as in another two windows:
<MenuItem x:Name = 'FileMenu' Header = '_File'>
<MenuItem x:Name = 'EnableAutostart' Header = '_Enable Autostart' IsChecked="{Binding AutoStart, Mode= TwoWay}" IsCheckable="true" ToolTip = 'Enables the autostart.' InputGestureText ='Ctrl+S'></MenuItem>
I use it to define whether or not the script automatically starts on user logon (a function checks for the scheduled activity and sets the checkbox accordingly) and when clicked it enables or disables it.
Now what if I want to keep all the 3 different windows checkboxes synced?
I read a lot about binding but can't really get it working, I tried to set the binding on a bool "Autostart" and to set it true before showing the window but it does nothing at all.
How can I define a bool in my code and make it so that, whenever I change that bool, it reflects on all the menuitems checkboxes bound to it? (even if the other windows are yet to be created/shown)
I read about needing to make it a property... can I just make a class, set a property to it called something like "AutoStart" and it would work?
Solution 1:[1]
Thank you @bluuf, you kind of gave me a hint.
Anyway comes out i actually achieved to do a databind previously in my many tests but as you said, the INotifyPropertyChanged is not so easy to handle in powershell, or maybe it is?
Good guy Trevor Jones (link at bottom) explained an easy way and i did the last steps to understand it and apply it to my code. Thank you Trevor.
He basically explains that this one collection:
System.Collections.ObjectModel.ObservableCollection[Object]
Has an already implemented iNotifyPropertyChanged that works well in powershell, without adding c# classes.
You just create that collection, add your bool to it, and point the binding.source to it.
Trevor's article, actually read it, worth your time: https://smsagent.blog/2017/02/03/powershell-deepdive-wpf-data-binding-and-inotifypropertychanged/
P.S. Trevor also points to this article which explains how to implement the c# class (and more), if anyone is interested: https://www.ephingadmin.com/better-know-a-powershell-ui-50-shades-of-bindings-part-1/
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Wyatt_LandWalker |