Input validation in textbox in windows phone 7 - c#

I am new to windows phone 7 development platform.I am trying to do validation for textbox input. On debugging ,in case of invalid input , I get the error "exception was unhandled".How to correct this?This code works fine for silverlight application.
TextBox Text="{Binding Name, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" />
private string _name;
public String Name
{
get { return _name; }
set {
if (string.IsNullOrEmpty(value))
{
throw new Exception("invalid name");
}
_name = value;
OnPropertyChanged("Name");
}
}

Have you tried to catch the invalid name Exception when trying to set an invalid value ?

I have had the same issue and found the following answer:
Make sure to not call the viewmodel's setter programmatically because in this case you have to take care of the exception, too.
If you let the data binding try to update the underlying viewmodel it also handles the exception for you.

Related

Xamarin Forms Picker raises two events

I have picker which is defined as:
<Picker
Title="Identifier"
ItemsSource="{Binding IdentifyUsing}"
SelectedItem="{Binding SelectedId}"
/>
And in ViewModel, SelectedId is configured as below:
public string SelectedId
{
get => _selectedId;
set
{
SetProperty(ref _selectedId, GetAppropriateLabel(value)); <-- This code is executed twice
IsEnabled = true;
}
}
where GetAppropriateLabel() method is defined as below:
private string GetAppropriateLabel(string value)
{
if (value.Contains("Member"))
return "Member ID (ex: 999999999)";
else if (value.Contains("Social"))
return "Social Security Number (ex: 999-99-9999)";
else if (value.Contains("StudentId"))
return "Medicare Number (ex: ********-**)";
else
return value;
}
Now, if I pass the value which is part of if-else chain, setter of SelectedId is executed twice. And second time, the value comes as null and breaks the app. If the value which is not part of if-else chain is passed, then it is works correctly.
I have no idea why setter of SelectedId is executed twice for the values which are not part of is-else chain.
Is this related to two way binding or picker related issues? Did I understand binding incorrectly? Any idea what is going wrong?

Syncfusion's Masked Edit keeps on appending the old value to the new value even after I create a new instance

I've encountered a weird interaction with Syncfusion's Masked Edit, it's a 3rd party WPF control that's basically a text box that takes a string mask and lets you choose how you'd want to interpret it (the one I currently set it to is RegEx) to filter out your text.
After creating a new NewCustomer through my Reset Command, if I try to type on a Masked Edit that had a value before creating the new instance it somehow still remembers that old value and appends it to the new value. Here's a clip of it (https://gfycat.com/embellishedpalefantail)
What I've tried:
I've tried removing the Mask and MaskType properties and ran the program to see if there was something else causing it but since it ran fine, the problem seems to lie on the Mask itself,
Could it be that they interpret my mask differently and it's behaving how they wanted it to?
Or is my Mask simply just wrong and it's interpreting it normally? Because with my mask of [0-9a-zA-Z ]{0,20}, I expected it to only allow alphanumeric characters and a space with a minimum length of 0 and maximum length of 20.
Here's a code of everything that's involved with my problem:
C#
The property the Text Value is bound to:
private Customer newCustomer;
public Customer NewCustomer
{
get { return newCustomer; }
set { newCustomer = value; RaisePropertyChanged("NewCustomer"); }
}
public class Customer : BaseSearchableCollectionClass
{
private string firstName;
public string FirstName
{
get { return firstName; }
set { firstName = value; RaisePropertyChanged("FirstName"); }
}
}
// The BaseSearchableCollectionClass contains the INotify implementation and other unrelated code
The reset command:
public RelayCommand ResetNewCustomerCommand { get; private set; }
public void ResetNewCustomer(object msg)
{
NewCustomer = new Customer();
}
public bool ResetNewCustomerCanUse(object msg)
{
if (HasChange() == true)
return true;
return false;
}
XAML
SFMaskedEdit:
<chart:SfMaskedEdit
Text="{Binding NewCustomer.FirstName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Mask="[0-9a-zA-Z ]{0,20}"
MaskType="RegEx"
/>
Reset Button:
<Button
Command="{Binding ResetNewCustomerCommand}"
Content="Reset"
/>
What I expected:
I expected it to run exactly like this:
I type something on the Masked Edit
Masked Edit filters out any unwanted characters and maintains length requirements
I press the reset button to create a New Customer, effectively clearing out any existing values
I type a new value on the Masked Edit as if it were a new text box (Unfortunately the problem lies here where it appends the cleared value to the new value)
The reported case is an defect with SfMaskedEdit control and we will include fix for issue in our upcoming release.
Regards,
Magesh S

IDataErrorInfo not updated

I encountered a problem with the IDataErrorInfo Interface and a wizard I'm currently programming.
The intention of my programm is to ask some Inputs ( usually done with a barcode scanner) and depending on the inputs start a specific sequence.
This is working as intendet. To make sure to catch wrong scans all inputs are check with an event ( OnValueParseFailed) If this event is triggered my current textbox is focused and all text selected:
this.MyWizardViewModel.ValueParseFailed += (s, e) =>
{
switch (e.Parameter)
{
case "ProductionOrder":
this.TextBoxProduction.Focus();
this.TextBoxProduction.SelectAll();
break;
The Interface itself is included this way:
public string this[string name]
{
get
{
string result = null;
if ((name == "ProductionOrder") && (!string.IsNullOrEmpty(this.ProductionOrder)))
{
if (this.System.FirmwareVersion == 0)
result = Lang.Strings.WrongEntry;
}
Its working for the first run. But if the wizard is finished or aborted and run a second time without closing the app, no error message is shown.
The Reset simply returns the app to default values.
public void ResetApplikation()
{
this.System.Clear(); // reset System values
this.ProductionOrder = string.Empty;
this.BmsTypeCode = string.Empty;
this.CellStack1TypeCode = string.Empty;
this.CellClass1 = string.Empty;
this.CellStack2TypeCode = string.Empty;
this.CellClass2 = string.Empty;
this.IsSystemProgrammed = false;
this.IsSystemParameterized = false;
this.MyMachine.Abort(); // reset wizard state
}
While debugging I can see the Interface to be handeled correctly. But no error is displayed.
In XAML the binding is set TwoWay
<TextBox Name="TextBoxProduction" Grid.Row="2" Width="200" Margin="10"
Style="{StaticResource TextBoxNormal}" Loaded="TextBoxProduction_Loaded"
Text="{Binding Path=ProductionOrder, ValidatesOnDataErrors=True,
NotifyOnValidationError=True, Delay=100,
UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" />
I'm using MahApps but as the textbox class is based on the wpf textbox I doubt a bug in this element is the problem. Any suggestions would be great.
Thank you.
The Answer of Domysee helped me.
Implementing INotifyDataErrorInfo instead of IDataErrorInfo was a major change but it fixed the problem!

Validate invalid input on DateTimePicker

I have a DateTimePicker as follows:
<UserControl
...
xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
...
>
<xctk:DateTimePicker Name="MyDatePicker"
Value="{Binding MyDate, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}"
Format="Custom" FormatString="dd/MM/yyyy HH:mm:ss"
AutoCloseCalendar="True"/>
I'm using IDateErrorInfo on my data model to handle business logic errors; for example:
public class MyViewModel : IDataErrorInfo
{
public string Error
{
get { return null; }
}
public string this[string columnName]
{
get
{
string error = DataValid();
CanExecute = (error == string.Empty);
return error;
}
}
CanExecute is a property which manages whether the user can select to submit the data. This all works well, however, if I simply select the date and mash the keyboard (type random letters), the date is reset to 01/01/01. What I would like to happen is for the date to effectively remain unchanged (that is, as it was before I mashed the keyboard). However, I can't seem to find a place to handle the casting error which obviously is occurring when this happens.
How can I trap this?
(The DateTimePicker control is part of the WPF Extension Kit)
If you don't like the way the control handles errors you can handle errors yourself in a subclass, an example of this in my old question Wpf Datepicker Input modification

RaisePropertyChanged fails to update the UI

I've been working on an application in MVVM Light lately. I have a TextBox in my XAML bound to my UI. I'd like to validate any input and ensure that only numbers are entered. I've tried the following code:
My TextBox:
<TextBox TabIndex="1" Height="23" MinWidth="410" DockPanel.Dock="Left"
HorizontalAlignment="Left"
Text="{Binding Input, UpdateSourceTrigger=PropertyChanged}"
IsEnabled="{Binding IsEnabled}"
AcceptsReturn="False"
local:FocusExtension.IsFocused="{Binding IsFocused}">
And in my ViewModel:
private string input;
public string Input
{
get { return this.input; }
set
{
decimal test;
if(decimal.TryParse(value, out test))
{
this.input = value;
}
else
{
this.input = "";
}
RaisePropertyChanged("Input");
}
}
This fails to update the UI. If I enter "B" and check the debugger, it runs through the setter, but fails to actually update the UI.
Curiously, if I set this.input = "TEST"; in the else block, the UI updates, but, if I attempt to set it to "", string.Empty, or the value of input before the validation, the UI fails to update.
Is this by design? Possibly a bug? Is there something I'm doing wrong?
Edit I mistakenly forgot to include RaisePropertyChanged in my example code. I've updated it. Raising it isn't the problem as I've watched the debugger run all the way through raising it and returning input via the getter.
Way you use strign type property and then convert to decimal, easier to change lik this:
public decimal Input
{
get { return this.input; }
set
{
this.input = value;
RaisePropertyChanged("Input");
}
}
And for validate use IDataErrorInfo (read more: http://blogs.msdn.com/b/wpfsdk/archive/2007/10/02/data-validation-in-3-5.aspx)
What we have done is created a Custom Control, since we use it for a Currency Text Box. I warn you I have no validation that this is a good idea, or falls in line with MVVM model because all manipulation of the control are done in code behind.
In the control on the textbox we have an event on PreviewTextInput that does this
e.Handled = Functions.DoubleConverter(Convert.ToChar(e.Text), ((TextBox)sender).Text.Replace("$", ""));
Then for the function (which isnt perfect, I have a few issues with it still) is:
static public bool DoubleConverter(char c, string str)
{
if (!char.IsDigit(c))
{
if (c == '.' && (str.Contains('.')))
{
return true;
}
else if (c != '.')
{
return true;
}
}
return false;
}
Please use this as a reference, not exactly as is because it is a very crude implementation.

Categories

Resources