how to set value of CheckBox to true in viewModel? [closed] - xamarin.forms

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
i want one checkbox to be by default checked. I have tried this but its not working. I have tried to set IsChecked true in xaml but then it doesnt get affected.
public bool FilterAlphabetically
{
set
{
NotifyPropertyChanged();
_filterAlphabetically = value;
_filterAlphabetically = true;
if (FilterAlphabetically)
{
UserDecision.Add(1);
FilterNotListened = false;
}
}
get => _filterAlphabetically;
}

Be sure to bind IsChecked to your property:
<CheckBox ... IsChecked="{Binding FilterAlphabetically}" ... />
and be sure to set the default value to true:
// bools are false by default
public bool FilterAlphabetically { ... } = true;

Related

Blazor Component parameter should not be set outside of its component

I am learning Blazor. I have no experience with component-based programming.
I have two components: a DateRangePicker and a RadzenCheckBox.
<RadzenFieldset Text="Test Component">
<DateRangePicker #ref="calendar" />
<div>
<Radzen.Blazor.RadzenCheckBox TValue="bool" Change="#((args) => txtBoxChange(args))" />
<RadzenLabel Text="Check" />
</div>
</RadzenFieldset>
Now, the requirement is simple. If the checkbox is clicked, show two calendars and show one calendar if it's unchecked.
I wrote the following code:
#code{
DateRangePicker calendar;
public void txtBoxChange(bool args)
{
if (args == true) //shows one calendar when checked
calendar.ShowOnlyOneCalendar = true;
else //shows two calendars when unchecked
calendar.ShowOnlyOneCalendar = false;
}
}
This works fine.
But I get a warning:
Component parameter 'ShowOnlyOneCalendar' should not be set outside of its component.
I have read some blogs about this warning, which suggest making parent and child component relationship for communication between components. But these are not parent and child.
What am I doing wrong?
What is the best way to achieve such a requirement and not have this warning?
What am I doing wrong?
Instead of using an imperative programming (component.Parameter1=v1) way, a Component Parameter is supposed be passed in declarative syntax :
<Component Parameter1="#v1" Parameter2="#v2" />
Note you're assigning values to [Parameter] directly:
calendar.ShowOnlyOneCalendar = true;
That's why Blaozr complains. In other words, you need change it in following way:
<DateRangePicker ShowOnlyOneCalendar="#showOnlyOne" />
How to fix
Always follow this pattern like other SPA:
(render)
Data -----------> View
For example, your code could be rewritten as below:
<DateRangePicker ShowOnlyOneCalendar="#flag" />
...
#code{
private bool flag = false;
public void txtBoxChange(bool args)=> flag = args;
}
(Here we have a flag data, and we should render the view according to the data)
Or if you do want to use an imperative programming way, you need to invoke a method and avoid assigning values to the [Parameter] properties directly.
<DateRangePicker #ref="calendar" />
...
#code{
DateRangePicker calendar;
public void txtBoxChange(bool args)
{
calendar.A_Wrapper_Method_That_Changes_The_Parameter(args);
// as suggested by #Uwe Keim,
// `InvokeAsync(StateHasChanged)` is better than `StateHasChanged()`
InvokeAsync(StateHasChanged);
}
}

asp.net mvc make model property required based off other property value [duplicate]

This question already has answers here:
How i do Required If validation by function in MVC5
(2 answers)
RequiredIf Conditional Validation Attribute
(7 answers)
Closed 4 years ago.
I have a model with two of the properties set to required using annotations. How would I make the second property required only if the first property is a certain value? I have been able to make it work for a blank form using JQuery but the problem lies when I prepopulate the form with data, it doesnt recognize the value of the first property thus not not setting the other property required or not.
Here is what my View and Javascript are doing currently...
...
<div class="form-group">
#Html.LabelFor(x => x.Property1)
#Html.DropDownListFor(x => x.Property1, Model.Prop1Values, "", new {#class ="form-group prop1"})
#Html.ValidationMessageFor(x => x.Property1)
</div>
<div class="form-group">
#Html.LabelFor(x => x.PropDependentOnProp1)
#Html.DropDownListFor(x => x.PropDependentOnProp1, Model.Prop2Values, "", new {#class ="form-group prop2"})
#Html.ValidationMessageFor(x => x.PropDependentOnProp1)
</div>
...
<script>
$(".prop1").on("change", function() {
var selected = $(this).find(":selected").val();
if(selected == "Y"){
$(".prop2").rules('add', {
required: true
});
} else {
$(".prop2").rules('add', {
required: false
});
}
</script>
This works for a new form but when data is prefilled in the model, the validation change does not go into effect until Property1 is changed. I have tried to put similar logic to above in $(document).ready but get "cant change undefined property 'settings'". I found a link to a possible workaround here to instantiate the validator first but this removes all validation for my other properties that need to be required and does not use the validation <span> tags from the Html Helper methods.
You can implement your own validation attribute and access the model using validation context. The following code is from dotnetmentors and should give you a good idea of how to modify it for your needs
using System.ComponentModel.DataAnnotations;
namespace FirstMVC.Models
{
public class ValidLastDeliveryDate : ValidationAttribute
{
protected override ValidationResult
IsValid(object value, ValidationContext validationContext)
{
var model = (Models.Customer)validationContext.ObjectInstance;
DateTime _lastDeliveryDate = Convert.ToDateTime(value);
DateTime _dateJoin = Convert.ToDateTime(model.JoinDate);
if (_dateJoin > _lastDeliveryDate)
{
return new ValidationResult
("Last Delivery Date can not be less than Join date.");
}
else if (_lastDeliveryDate > DateTime.Now)
{
return new ValidationResult
("Last Delivery Date can not be greater than current date.");
}
else
{
return ValidationResult.Success;
}
}
}
}

How to create a stylesheet dynamically and add that to a node [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Currently JavaFX does not allow attaching a stylesheet to a node (or scene) that is not in the classpath. So, if a css file is not in the classpath already, it cannot be added to any node. The getStyleSheets().add() method will state 'WARNING Resource [your file] not found'. So is there any workaround to this limitation?
Not sure if this is what you are looking for...
Button node = new Button();
node.getStyleClass().add("my-new-style-class");
.my-new-style-class {
-fx-padding: 5;
}
The idea is to create a temporary stlyesheet file, write the new style-class inside, add the style-sheet to the list of sheets of the node and add also the new style-class.
Here is a working example:
Button button = new Button("My Text");
button.setOnAction(e -> {
try {
// Create a new tempfile that will be removed as the application exits
File tempStyleClass = File.createTempFile("AppXY_TempStyleClass", ".css");
tempStyleClass.deleteOnExit();
// Write the stlye-class inside
try (PrintWriter printWriter = new PrintWriter(tempStyleClass)) {
printWriter.println(".temp-style { -fx-text-fill: red; }");
}
// Add the style-sheet and the style-class to the node
button.getStylesheets().add(tempStyleClass.toURI().toString());
button.getStyleClass().add("temp-style");
} catch (IOException e1) {
e1.printStackTrace();
}
});
Well, It's late, 2 years late, but maybe it helps someone.
The idea is this:
object.setStyle("[your CSS code]");
Example to give a background color red to an object called "node":
node.setStyle("fx-background-color: red");
I hope it helps somebody.

Rewiring actions of parent to a child viewmodel

So here's my screnario. I have a toolbar at the top (office style), with buttons. This is hosted in a shell. Some of those buttons are applicable only to certain child view models as they get loaded. Ideally what I would like to happen is have the buttons action.target repositioned to child view model as it gets created (I kind of got this working by settings Action.Target="ActiveItem" on them. This doesn't solve the problem fully though:
a) When the child viewmodel is closed and there is no active item, I want them to reposition to Shell as the target so they can be set to "default" state.
b) I noticed that when child viewmodel is closed and the shell being the conductor has it ActiveItem=null, the hooks from the action are still bound to the living instance of the last viewmodel, so doesn't looks like it got disposed of. Memory leak?
Any suggestions how to implement this scenario?
What about adding a property to your ShellViewModel which points to the action target and updating it when stuff gets activated/deactivated:
e.g.
public class ShellViewModel
{
public object ActionTarget
{
get { return _actionTarget; }
set
{
_actionTarget = value;
NotifyOfPropertyChange(() => ActionTarget);
}
}
// Then when the active item changes just update the target:
public override NotifyOfPropertyChange(string propertyName)
{
if(propertyName == "ActiveItem")
{
if(ActiveItem == null) ActionTarget = this;
else ActionTarget = ActiveItem;
}
}
}
Now bind to that:
<SomeMenu cal:Action.Target="{Binding ActionTarget}" />
Not sure if that will work or not but I'm sure I've done something similar in the past. (You may also have to explicitly call NPC on your actions before they will update after you have changed ActiveItem)

Use actionscript to uncheck a checkbox in a component?

I have a component with checkboxes, the checkboxes are bound to booleans in the main code:
<mx:CheckBox id="LyrClearAll" selected="{Application.application.bLyrClearAll}"/>
This works fine for the checkboxes that don’t change unless a user interacts with them again. My problem appears because I want to “uncheck” one of the boxes everytime the component is closed. (I know something other than a checkbox would work better, but I’m trying to keep things consistent in this component.)
I have tried setting the bound Boolean variable to false, and I’ve tried setting the checkbox.selected value to false. Neither are working, everytime I open the component the checkbox is still checked.
private function makeLyrsPopUp(evt:MouseEvent):void
{
var panelLyr:popUpLayers = PopUpManager.createPopUp(this, popUpLayers, false) as popUpLayers;
panelLyr.LyrClearAll.selected == false; //?? set checkbox back to unchecked
panelLyr["cancelButton"].addEventListener("click", removeMe);
panelLyr["okButton"].addEventListener("click", submitData);
PopUpManager.centerPopUp(panelLyr);
function submitData(event:Event):void //change layer visibility based on check boxes in popupLayer
{
bLyrStreet = panelLyr.LyrStreet.selected;
bLyrParcel = panelLyr.LyrParcel.selected;
bLyrClearAll = panelLyr.LyrClearAll.selected;
if (bLyrClearAll)
{
clearLayers();
bLyrClearAll == false; //?? set checkbox back to unchecked
}
removeMe(event);
}
}
Needed to change == false to = false
bLyrClearAll should be declared bindable:
[Bindable]
var bLyrClearAll: Boolean;

Categories

Resources