Add some way to specify indeterminate checkboxes in blazor - core

Add some way to specify indeterminate checkboxes in blazor.
I have tried below is not worked
<input type="checkbox" indeterminate="#checkValue" onclick="#checkedClick" />
Any one specify indeterminate checkboxes in blazor.

I seems this is not planned for a while. (see https://github.com/dotnet/aspnetcore/issues/10378)
The minimal solution I have found is this ...
Component code
#inject IJSRuntime jsRuntime
<input #ref=inputElement type="checkbox" checked="#Checked" #onchange="OnChange" />
#code {
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (Indeterminate.HasValue)
{
await jsRuntime.SetElementProperty(inputElement, "indeterminate", Indeterminate.Value);
}
await base.OnAfterRenderAsync(firstRender);
}
private ElementReference inputElement;
[Parameter]
public bool? Indeterminate { get; set; }
[Parameter]
public bool Checked { get; set; }
[Parameter]
public EventCallback<bool> CheckedChanged { get; set; }
private async Task OnChange(ChangeEventArgs e)
{
Checked = (bool)e.Value;
await CheckedChanged.InvokeAsync(Checked);
}
}
Interop C# code
public static async Task SetElementProperty(this IJSRuntime jsRuntime, ElementReference element, string property, object value)
{
await jsRuntime.InvokeVoidAsync("window.jsinterop.setPropByElement", element, property, value);
}
Interop Javascript code
window.jsinterop = {
setPropByElement: function (element, property, value) {
element[property] = value;
}
}

Related

WPF PRISM 6 DelegateComand ObservesCanExecute

Thanks in advance!
How should I use ObservesCanExecute in the DelegateCommand of PRISM 6?
public partial class UserAccountsViewModel: INotifyPropertyChanged
{
public DelegateCommand InsertCommand { get; private set; }
public DelegateCommand UpdateCommand { get; private set; }
public DelegateCommand DeleteCommand { get; private set; }
public UserAccount SelectedUserAccount
{
get;
set
{
//notify property changed stuff
}
}
public UserAccountsViewModel()
{
InitCommands();
}
private void InitCommands()
{
InsertCommand = new DelegateCommand(Insert, CanInsert);
UpdateCommand = new DelegateCommand(Update,CanUpdate).ObservesCanExecute(); // ???
DeleteCommand = new DelegateCommand(Delete,CanDelete);
}
//----------------------------------------------------------
private void Update()
{
//...
}
private bool CanUpdate()
{
return SelectedUserAccount != null;
}
//.....
}
Unfortunatelly, I'm not familiar with expressions in c#. Also, I thought this would be helpful to others.
ObservesCanExecute() works “mostly like” the canExecuteMethod parameter of DelegateCommand(Action executeMethod, Func<bool> canExecuteMethod).
However, if you have a boolean property instead of a method, you don't need to define a canExecuteMethod with ObservesCanExecute.
In your example, suppose that CanUpdate is not a method, just suppose that it's a boolean property.
Then you can change the code to ObservesCanExecute(() => CanUpdate) and the DelegateCommand will execute only if the CanUpdate boolean property evaluates to true (no need to define a method).
ObservesCanExecute is like a “shortcut” over a property instead of having to define a method and having passing it to the canExecuteMethod parameter of the DelegateCommand constructor.

Caliburn CanExecute not working even though firing

Trying to implement simple validation with caliburn. All I want is to enable/disable save button based on certain conditions.
View:
`<xctk:MaskedTextBox x:Name="pm_personId" cal:Message.Attach="[Event LostFocus] = [Action CanSave()]" Mask="00-000-000?"/>
<Button Content="Save" x:Name="Save" />`
Model:
public class PersonModel
{
public String personId { get; set; }
public PersonModel() {}
public PersonModel(String id)
{
this.id = personId;
}
}
ViewModel:
[ImplementPropertyChanged]
public class PersonViewModel : Screen
{
public PersonModel pm { get; set; }
public PersonViewModel()
{
pm = new PersonModel();
}
public bool CanSave()
{
MessageBox.Show(pm.personId);
if (pm.personId != null)
return true;
else return false;
}
}
The MessageBox is fired with the right value but button is not enable. Am I missing anything. Either am missing something with caliburn or it's doing too much magic. Am beginning to suspect that the time it may save you initially will be lost in debugging, just my exeprience.
Thanks #CCamilo but your answer was incomplete. For other people who encounter a similar problem, below is my final working code:
[ImplementPropertyChanged]
public class PersonModel
{
public String personId { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
public PersonModel() {}
public PersonModel(String id)
{
this.id = personId;
}
}
[ImplementPropertyChanged]
public class PersonViewModel : Screen
{
public PersonModel pm { get; set; }
public PersonViewModel()
{
pm = new PersonModel();
this.pm.PropertyChanged += pm_PropertyChanged;
}
void pm_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
NotifyOfPropertyChange(() => CanSave);
}
public bool CanSave
{
get { return pm.personId != null; }
}
}
The error you have is with CanSave() method.. It should be a property instead:
public bool CanSave
{
get
{
if (pm.personId != null)
return true;
else return false;
}
}

getter setter member variable not visible salesforce

When I bind data with custom controller, the following code works well.
public class searchContactCtrl {
String searchText;
public String getSearchText(){
return searchText;
}
public void setSearchText(String s ){
searchText =s;
}
}
but if I changed getter method of "searchText" as below, an error was occured.
public class searchContactCtrl {
public String searchText{get;}
public void setSearchText(String s ){
searchText =s;
}
}
Error message:
Compile Error: member variable not visible for assignment
Why is this happening?
You will need to define a private setter for the searchText property. E.g.
public class searchContactCtrl {
public String searchText {
get;
private set;
}
public void setSearchText(String s) {
searchText = s;
}
}
Or you could just remove the private modifier and directly set searchText without the setSearchText method.

How to remove one or more fields from the DataForm.Validating() event in Silverlight 4?

I have a data form that is bound to an object whose properties are decorated with System.ObjectModel.DataAnnotation attributes for validaton.
The problem I am facing is that some properties of this class are only conditionally needed and do not need to be validated. For example when an admin of the app decides to edit a user,
he or she may enter a password/password confirm/password question/password answer. Or he/she may entirely skip those properties.
So if the admin decides to enter any of those 4 fields, they all have to be present and the validation rules for all these fields have to be applied. However if the admin only wants to change the FirstName, LastName, Email, or whatever other arbitrary properties - the password related fields do not need to be validated.
Is there a way to "Exclude" them from the validation process?
this is a sample of the object I work with:
public class RegistrationData
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string PasswordConfirm { get; set; }
public string PasswordQuestion { get; set; }
public string PasswordAnswer { get; set; }
}
I have a DataForm called registrationForm in the Xaml and the error I get is in this code:
private void RegistrationButton_Click(object sender, RoutedEventArgs e)
{
if( this.registerForm.ValidateItem() )
{
//Does not pass validaton if the password properties are not filled in.
}
}
Any ideas on how to fix it?
I was thinking of using two DataForms... and split the user object in two, but that involves a lot of code...
I would recommend to use the INotifyDataError interface on your RegistrationData object.
public string LabelWrapper
{
get
{
return this.Label;
}
set
{
ValidateRequired("LabelWrapper", value, "Label required");
ValidateRegularExpression("LabelWrapper", value, #"^[\w-_ ]+$", "Characters allowed (a-z,A-Z,0-9,-,_, )");
this.Label = value;
this.RaisePropertyChanged("LabelWrapper");
}
}
public string DependentLabelWrapper
{
get
{
return this.DependentLabel;
}
set
{
if(LabelWrapper != null){
ValidateRequired("DependentLabelWrapper", value, "Label required");
ValidateRegularExpression("LabelWrapper", value, #"^[\w-_ ]+$", "Characters allowed (a-z,A-Z,0-9,-,_, )");
}
this.DependentLabel = value;
this.RaisePropertyChanged("DependentLabelWrapper");
}
}
I recommend you to look at this link http://blogs.msdn.com/b/nagasatish/archive/2009/03/22/datagrid-validation.aspx to learn more about different validation types.
Also MSDN has a nice explanation on how to use it
http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifydataerrorinfo%28VS.95%29.aspx
This question brought me to another solution. I now use CustomValidation:
[CustomValidation(typeof(RegistrationDataValidation), "ValidatePassword")]
public class RegistrationData
{
public bool IsNewUser { get; set; }
... // other registration properties
}
public static class RegistrationDataValidation
{
public static ValidationResult ValidatePassword(MembershipServiceUser user, ValidationContext context)
{
if (user.IsNewUser && string.IsNullOrEmpty(user.Password))
{
return new ValidationResult("Password required");
}
return ValidationResult.Success;
}
}
I added a property IsNewUser which I set in the client when adding a new user. The custom validation method checks this property and executes the desired validation. I still have a RegularExpression Attribute on the password which will be validated as well.
In comparison to #Staindart's solution this is checked on the client synchronously.
The simplest and ugliest way would be to tap into the DataForm.ValidatingItem event. Like so:
void dfEditForm_ValidatingItem(object sender, System.ComponentModel.CancelEventArgs e)
{
foreach (ValidationSummaryItem item in dfEditForm.ValidationSummary.Errors)
{
if (item.Sources.Where(W => W.PropertyName != "myIgnoredPropertyName").Count() > 0)
e.Cancel = true;
}
}

DomainContext sometimes still HasChanges after SubmitChanges completes

I have a very simple server model that includes a parent entity with a [Composition] list of child entities. In my client, I have 2 functions. One function removes all the child entities from the parent and the other removes all and also edits a property on the parent entity.
When I simply remove all child entities and SubmitChanges(), all is well.
When I remove all child entities and edit the parent and SubmitChanges(), there are still pending changes (HasChanges == true) when the SubmitChanges() callback is fired.
I am using Silveright 4 RTM and RIA Services 1.0 RTM.
Any ideas what is going on here?
Here are the server entities:
public class RegionDto
{
public RegionDto()
{
Cities = new List<CityDto>();
}
[Key]
public int Id { get; set; }
public string Name { get; set; }
[Include]
[Composition]
[Association("RegionDto_CityDto", "Id", "RegionId")]
public List<CityDto> Cities { get; set; }
}
public class CityDto
{
[Key]
public int Id { get; set; }
public int RegionId { get; set; }
public string Name { get; set; }
}
And here is the client code:
public static class CState
{
private static RegionDomainContext _domainContext;
public static RegionDomainContext DomainContext
{
get
{
if (_domainContext == null)
{
_domainContext = new RegionDomainContext();
}
return _domainContext;
}
}
public static void SaveChanges()
{
DomainContext.SubmitChanges(op =>
{
if (DomainContext.HasChanges && !DomainContext.IsSubmitting)
{
var w = new ChildWindow();
w.Content = "The DomainContext still has unsaved changes.";
w.Show();
}
}, null);
}
}
public partial class MainPage : UserControl
{
private void ClearCitiesEditRegion(object sender, RoutedEventArgs e)
{
var region = (RegionDto)regionList.SelectedItem;
if (region != null)
{
region.Name += "*";
while (region.Cities.Count > 0)
{
region.Cities.Remove(region.Cities.First());
}
CState.SaveChanges();
}
}
private void ClearCities(object sender, RoutedEventArgs e)
{
var region = (RegionDto)regionList.SelectedItem;
if (region != null)
{
while (region.Cities.Count > 0)
{
region.Cities.Remove(region.Cities.First());
}
CState.SaveChanges();
}
}
}
When you run this code the ChildWindow is only shown when you the ClearCitiesEditRegion() method is called. The only difference between this and the ClearCities() method is the line where I edit the region.Name property.
You can also download a sample project that reproduces this here: http://dl.dropbox.com/u/2393192/RIA_Services_Problem.zip
I received an answer to this on the Silverlight forums. Apparently this is a bug in RIA Service 1.0. The following is Matthew's response on the Silverlight forums.
Yes, I've confirmed this is a bug.
Thanks for reporting it and providing
the repro. As you discovered, the bug
will only repro in composition
scenarios where the parent has been
modified in addition to one or more
children. The workaround is to do an
explicit AcceptChanges if the submit
was successful. For example, here is
the code you'd write in a submit
callback:
if (!submitOperation.HasError)
{
((IChangeTracking)ctxt.EntityContainer).AcceptChanges();
}
This will accept all changes and reset
change state correctly.

Resources