WPF CheckBox Binding - Altering value in Property Set does not affect UI - wpf

i have a simple checkbox
<CheckBox IsChecked="{Binding ForceInheritance}"/>
In Code i have a class with "INotifyPropertyChanged" and the Property
public bool ForceInheritance
{
get { return forceInheritance; }
set
{
if (forceInheritance != value)
{
value = SomeTest();
if (forceInheritance != value)
{
//something is done here.
}
OnPropertyChanged("ForceInheritance");
}
}
}
If SomeTest() returns !value so the underlying data does not have to change the CheckBox still changes its IsChecked state.
For example:
ForceInheritance is false.
CheckBox is clicked.
SomeTest() returns false.
--> The underlying data is not changed
--> I would expect the CheckBox to stay unchecked
The CheckBox gets checked.
What can i do to not change the IsChecked state of the CheckBox when the setter does not actually change the value?
I thought the "OnPropertyChanged("ForceInheritance");" would do the trick but it didn't.
Thank you for your time.

This problems occurs because when you click checkbox it s value is changed. Then binding causes property set. There you manipulate with its value and hope that calling OnPropertyChanged will cause back binding action updating checkbox value. But doesn't work because updating control after updating property may produce infinite updating loop. To prevent this PropertyChanged is ignored.
What can you do is to move some logic of your property setter to binding validation rule. You can read here about validation rules or leave a comment if you need more information or examples.
Hope it helps.

I would expect the CheckBox to stay unchecked
Now, it seems that CheckBox working as you expect. Something must have changed recently because it works differently now.
Previously
When I needed to correct a value in the setter I use Dispatcher.
public bool IsActive
{
get => _isActive;
set
{
if (_isActive != value)
{
if (value)
{
if (!CanActive())
{
Application.Current.Dispatcher.BeginInvoke((Action)(() => IsActive = false));
return;
}
}
_isActive = value;
OnPropertyChanged(nameof(IsActive));
}
}
}
Now
Now, I don't have to change a value back to false. This works even if I remove OnPropertyChanged call, because after the setter is called, the getter is also called. It looks like the CheckBox is now correcting its state.
public bool IsActive
{
get => _isActive;
set
{
if (_isActive != value)
{
if (value)
{
if (!CanActive())
{
return;
}
}
_isActive = value;
OnPropertyChanged(nameof(IsActive));
}
}
}

Related

Why is getValue() always returning false?

I filled a list with a CheckBox. This Checkbox is screnning on the page. Then i will find out, if the Checkbox is checked or not. But this is Always returning false, even when the Checkbox is pressed. But why?
ArrayList<TutorialAnswerCheckbox> cbList = new ArrayList<>();
cbList.add(new TutorialAnswerCheckbox(false, "Zuweisungsoperatoren"));
Here the Checkbox is created.
public TutorialAnswerCheckbox(boolean isCorrectAnswer, String text)
{
this.isCorrectAnswer = isCorrectAnswer;
setText(text);
getElement().getStyle().setColor("black");
getElement().getStyle().setProperty("float", "left");
}
Here im adding the box to my HTMLPanel to a answer div.
html.add(cbList.get(0), "answer9");
This works. Then when the user hits a button i will check if the checkbox is pressed or not.
#UiHandler("abgabe")
void done(ClickEvent e)
{
Window.alert(cbList.get(0).isAnswerCorrectly.toString());
}
public boolean isAnswerCorrectly()
{
return this.getValue();
}
But the window alert is Always false
This Returns also false even when it is checked.
Window.alert(cbList.get(0).isAnswerCorrectly.toString());
you have to set the fireEvents checkbox.setValue(value, fireEvents);

setState not updating when set to boolean

I have the following method in a react component:
handleCheckBoxClick() {
var checkbox = document.getElementById("boldCheckbox").checked;
this.setState({ischecked : checkbox});
if(this.state.ischecked) {
this.setState({weight:'bold'});
} else {
this.setState({weight:'normal'});
}
}
but if I change the if statement to:
if(checkbox) {
this.setState({weight:'bold'});
} else {
this.setState({weight:'normal'});
}
it works fine but I can't figure out why the first way doesn't work.
The method setState() is asynchronous, and updates are often batched together. In your case, ischecked is updated together with the weight, so when you set the weight you still refer to the old value.
One solution is to use setState()'s callback that will be called after the state is updated.
Note: to get the checkbox checked state, use the event object e passed to the handler instead of querying the DOM.
handleCheckBoxClick(e){
var checked = e.target.checked;
this.setState({ischecked : checked}, function() {
if(this.state.ischecked){
this.setState({weight:'bold'});
}else{
this.setState({weight:'normal'});
}
});
}
A better solution is to update both properties because you know if the checkbox is checked:
handleCheckBoxClick(e){
var checked = e.target.checked;
this.setState({
ischecked : checked,
weight: checked ? 'bold' : 'normal'
});
}
Thats cause this.setState({ isChecked : checkbox }); has not finished before you ask it in the if statement.

ANGULAR2: Detecting Change in static variable of a class

I am writing a dragDirective. Eements are dragged in dragZones. On mouse releases I do a hitTest against all availabe dragZones. I am maintaining a static boolean flag which ends up being false if all hittests return false. In such a situation I would like to resposition the element in the dragZone it originally belonged to. How do I check against this change in variable value?
this._messageBus.listen("dragStart", (obj, event) => {
DragZoneDirective.HITTEST = false;
});
this._messageBus.listen("dragStop", (obj, event) => {
if (this.hitTest(event.x, event.y))
{
//clone object
let clone: Object = JSON.parse(JSON.stringify(obj));
this.dragZoneElems.push(clone);
DragZoneDirective.HITTEST = true;
}
let index = this.dragZoneElems.indexOf(obj);
if (index > -1)
this.dragZoneElems.splice(index, 1);
});
You can't use Angular binding that is checked by Angular change detection on static fields.
You could add a getter on a component that forwards to that static field, then a binding to that getter would be checked by Angulars change detection.
IMHO the preferred way is to use an Observable that emits an event on change. Interested code can subscribe and get notified about updates.

CustomValidation Annotation Event Raise Issue MVVM Silverlight 5

I've Created a Model which have few custom validation. These custom validation I've annotated at property by below code
[CustomValidation(typeof(ItemmasterModel), "ValueTextMaxLenghtValidate")]
public decimal Valuetextmaxlength
{
get
{
return _Valuetextmaxlength;
}
set
{
ValidateProperty("Valuetextmaxlength",value);
_Valuetextmaxlength = value;
RaisePropertyChanged(() => Valuetextmaxlength);
}
}
public static ValidationResult ValueTextMaxLenghtValidate(object obj, ValidationContext context)
{
var itmmstr = (ItemmasterModel)context.ObjectInstance;
if (itmmstr.SelectedValuetypeDd != null)
{
string vtype = itmmstr.SelectedValuetypeDd.Key.ToString();
if (vtype.Equals("C"))
{
if (itmmstr.SelectedItemValueCodeTypesDd != null)
{
string vcode = itmmstr.SelectedItemValueCodeTypesDd.Key.ToString();
if (vcode.Equals("T"))
{
if (itmmstr.Valuetextmaxlength == null || itmmstr.Valuetextmaxlength == 0)
{
return new ValidationResult("Value Max Length is not Entered",
new List<string> { "Valuetextmaxlength" });
}
}
}
}
else if (vtype.Equals("T"))
{
if (itmmstr.Valuetextmaxlength == null || itmmstr.Valuetextmaxlength == 0)
{
return new ValidationResult("Value Max Length is not Entered",
new List<string> { "Valuetextmaxlength" });
}
}
}
return ValidationResult.Success;
}
Now this validation code depend on other property. scenerio When User select a value from dropdown it makes 1 checkbox selected automatically and User should enter the value in texbox also.
Issue:
Validation is working. checkbox is selected at first time then also it comes with error popup.
untill user doesn't make changes into this checkbox or texbox it is with error only. 1 time it says error even value has been entered .Next time it goes even user have not entered anything but during final full object validation is again comes with error.
Why this even ambiguity is happening. How to solve this.
Need more code let me know. I'll Post. Code is in Silverlight 5, MVVM Light
During my Custom validation I was using ValidateProperty("Valuetextmaxlength",value); before setting the value of property so It was giving me issue but the moment I set the value first and then Use my ValidateProperty("Valuetextmaxlength",value); everything worked smooth. Still I don't know the reason why but It worked for me.

Smartgwt: How to get checkbox value on a listgrid?

I've a listener on cellClick, I get the selected Record but I can't find a way to understand if this record is checked
Method ListGrid.isSelected(ListGridRecord) returns true if row is selected, not if is checked
My Code:
listGrid.setSelectionAppearance(SelectionAppearance.CHECKBOX);
listGrid.addCellClickHandler(new CellClickHandler() {
#Override
public void onCellClick(CellClickEvent event) {
if(event.getColNum() == 0 && idMenu != null){
boolean isChecked = event.getRecord().???;
if(isChecked)
....
else
....
}
I've tried also with event.getRecord().getAttributeAsBoolean("_checkField") with no success...
I found a simply solution...
My task is solved using a special boolean field in the DataSource named, for example, "checked"
In ListGrid I've a field "checked", and with a RecordClickHandler I can manage check or uncheck event.
DataSource code:
DataSourceBooleanField checkField = new DataSourceBooleanField("checked");
ListGrid code:
listGrid.addRecordClickHandler(new RecordClickHandler() {
#Override
public void onRecordClick(RecordClickEvent event) {
Record rec = event.getRecord();
boolean checked = rec.getAttributeAsBoolean("checked");
if(checked){
...
}else{
...
}
rec.setAttribute("checked", !checked);
catPgrid.saveAllEdits();
catPgrid.refreshFields();
}
});
ListGridField checkField = new ListGridField("checked", "Sel");
Maybe getSelectedRecords() method would help you!
Here is an API reference: http://www.smartclient.com/smartgwt/javadoc/com/smartgwt/client/widgets/grid/ListGrid.html#getSelectedRecords()
Definitely this will provide all records which are selected (using checkbox) but there should be some values which you could use for identifying each record uniquely!

Resources