I have the following textbox , not sure why the formatting won't go to normal but you get the point.
<TextBox LostFocus="TextBox_LostFocus">
<TextBox.Text>
<Binding Path="InputVolts"
TargetNullValue=''
FallbackValue=''>
<Binding.ValidationRules>
<u:NonEmptyStringValidator/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
This textbox is bound to the following property:
public int? InputVolts
{
get { return _InputVolts; }
set { Set(ref _InputVolts, value);}
}
In my form, if I type a number like 240 into the textbox the view model will update with that value. If I try and delete the 240 from the textbox, the view model does not update the InputVolts property accordingly.
I am aware of the TargetNullValue solution from the following Post
EDIT:
Okay I found the problem, my NonEmptyStringValidator is causing this issue. I want to still have this validation rule on my text box though. Is there anyway to adjust this to still keep the validation rule but make the textbox return back to null when deleted?
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
ValidationResult validationResult = new ValidationResult(false, "Value cannot be empty.");
if (value != null)
{
string valueAsString = value as string;
if (valueAsString.Length > 0)
validationResult = ValidationResult.ValidResult;
}
return validationResult;
}
I also tried using the FallBackValue and nothing seems to be working. Any help would be greatly appreciated!
Thank you,
The <u:NonEmptyStringValidator/> might prevent the update to an empty string.
Related
I have a ComboBox like this:
<ComboBox Name="TipoVisitante" ItemsSource="{Binding TiposVisitante}" SelectedValue="{Binding TipoVisitante}" Style="{StaticResource ComboBoxStyle}">
<ComboBox.Text>
<Binding Path="TipoVisitante" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<validations:SimpleIsRequiredValidation/>
</Binding.ValidationRules>
</Binding>
</ComboBox.Text>
</ComboBox>
This ComboBox is binded to the TipoVisitante property from the ViewModel. The TipoVisitante variable looks like this:
private string _TipoVisitante;
public string TipoVisitante {
get =>_TipoVisitante;
set {
if (ValidarTipoVisita(value) == true) {
_TipoVisitante = value;
OnPropertyChanged();
}
else {
MessageBox.Show("YA EXISTE UNA VISITA ÍNTIMA ACTIVA", "VISITA INTIMA ACTIVA", MessageBoxButton.OK, MessageBoxImage.Error);
_TipoVisitante = null;
OnPropertyChanged();
}
}
}
When TipoVisitante is set, I want to check if the value is valid using a method that return true or false depending on which the value is valid or not. If the the values isn't valid, I show a message saying that the value is not valid. The problem is, because of the validation on rule on the ComboBox, the set property of the TipoVisitante variable is called twice, and the error message is shown twice. The Validation Rule of the ComboBox looks like this:
public class SimpleIsRequiredValidation: ValidationRule {
public override ValidationResult Validate(object value, CultureInfo cultureInfo) {
if (!string.IsNullOrEmpty(value ? .ToString()))
return new ValidationResult(true, null);
else
return new ValidationResult(false, null);
}
}
The validation rule checks if the user has selected some value of the combobox, checking if the text is null or a empty string. Also in my code behind I have this:
private void Button_Click(object sender, RoutedEventArgs e) {
if (string.IsNullOrWhiteSpace(TipoVisitante.Text))
TipoVisitante.Text = "";
}
This method is the Click property of a button. When the button is click, I check if the user hasn't selected some value of the ComboBox I set the text to empty string to trigger the validation and show the red border in the ComboBox.
How can I avoid the setter of the binded variable TipoVisitante to be called twice?
Try to add extra property that check was it called once then use it to block call it twice.
The solution was change the validation from ComboBox.Text to ComboBox.SelectedValue. After that in the button Click action, change TipoVisitante.Text = "" to TipoVisitante.SelectedValue = null. Doing that it worked fine.
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.
How do I use an IValueConverter to convert nulls into booleans?
I'm using wpf to try to display a bunch of boolean values (in checkboxes). When a new record is created, these values are null, and appear as 'indeterminate' in the checkboxes. I want the nulls to appear and save as 'false' values.
I tried to create a NullToBoolean converter that takes null values from the database and displays them as false, and then saves them as false when the user hits save. (Essentially, I'm trying to avoid the user having to click twice in the checkboxes (once to make it true, then again to make it false). This seems to work on import - ie null values are shown as false - but unless I do the two-click dance the value doesn't change in the database when I save.
My Converter:
[ValueConversion(typeof(bool), typeof(bool))]
public class NullBooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value != null)
{
return value;
}
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value != null)
{
return value;
}
return null;
}
}
One of the checkboxes I'm trying to have the Converter work with:
<CheckBox Grid.Column="1" Grid.Row="0" Padding="5" Margin="5" VerticalAlignment="Center" Name="chkVarianceDescriptionProvided" IsThreeState="False">
<CheckBox.IsChecked>
<Binding Path="VarianceDescriptionProvided" Mode="TwoWay">
<Binding.Converter>
<utils:NullBooleanConverter />
</Binding.Converter>
</Binding>
</CheckBox.IsChecked>
</CheckBox>
I don't know if the problem is because my code is wrong, or if it's a case of the Converter thinking that nothing has changed, therefore it doesn't need to ConvertBack. I have tried all the Modes and switched code in Convert with ConvertBack, but nothing seems to work.
Can someone point out what I need to do to fix this?
Hmm, why using a converter, if you can have it out of the box?
<CheckBox IsChecked="{Binding VarianceDescriptionProvided, TargetNullValue=False}" />
For more information, pls have a look here.
The real problem is the fact you are not initializing your data objects in the first place. Don't "fix", do it right to begin with; builders are good (for example). You also should be making ViewModels/DataModels rather than working with your Models (database, etc) directly.
public class MyObjectBuilder
{
Checked _checked;
public MyObjectBuilder()
{
Reset()
}
private void Reset()
{
_checked = new Checked(true); //etc
}
public MyObjectBuilder WithChecked(bool checked)
{
_checked = new Checked(checked);
}
public MyObject Build()
{
var built = new MyObject(){Checked = _checked;}
Reset();
return built;
}
}
then always initialise with the builder
myObjects.Add(new MyObjectBuilder().Build());
or
myObjects.Add(_injectedBuilder.Build()); // Initialises Checked to default
myObjects.Add(_injectedBuilder.WithChecked(true).Build()); //True
While this doesn't fix your asked problem, it will fix your underlying problem in a way you can Unit Test. i.e. you can test to ensure the values added into your object list are always initialized.
Simply correct your data before you perform data binding. That is the only option. The converter will only work make the check box show as 'unchecked' and update your data only when you interact with the control. For example:
foreach (var item in items)
{
if (item.VarianceDescriptionProvided == null)
item.VarianceDescriptionProvided = false;
}
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.
Hi I am trying to set the visibility of a label based on a textbox string being empty. I have the following code:
MyLabel.Visible = String.IsNullOrEmpty(MyTextBox.Text);
Why does MyLabel not appear when the textbox is left empty?
Update
I have tried placing this code in the Text_Changed event of the textbox and it still doesn't work.
This was an update issue, it does work on the Text_Changed event. However the issue is it does not work when triggered on the proccessing of the form.
Here is the code triggered from my controller class to give everyone a better insight as to what is going on:
using (var frm = new frmAdd(PersonType.Carer))
{
var res = frm.ShowDialog();
if (res == System.Windows.Forms.DialogResult.OK)
{
if (frm.ValidateInformation()) // the above code is called in here
{
// process the information here...
}
}
}
Also I forgot to mention that this form is in a Class Library project (dll).
Depends on where the code is being run. If you need interactivity, i.e. the label disappears when a character is typed into the textbox, you need to run it on the Keyup event of the textbox. You may also need to repaint the label.
If you are updating the Visible property in the text changed event you are probably running into the following problem. When the form first starts up the text is set to an empty string. But because this is the initial value it hasn't changed so to speak and hence no event is raised.
You may need to perform this update directly in your Form constructor. See if that fixes the problem.
I would add a Trim, to be more consistent to the User in case of spaces left:
MyLabel.Visible = String.IsNullOrEmpty(MyTextBox.Text.Trim());
For the rest it is a matter of triggering the code at the right time. TextChanged should cover everything but the inital state, as addressed by JaredPar. Although I would use Form_Load, not the constructor.
Edit, after the clarification: If your Label an TextBox are on frmAdd then the question is moot, the form itself is no longer shown after ShowDialog returns.
I suspect you want to use data binding to set the visibility of the label.
This discussion might help you: WPF Data Binding : enable/disable a control based on content of var?
Update, some code:
public string MyText
{
get { return _myText; }
set { _myText = value; OnPropertyChanged("MyText"); }
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private void theTextBox_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
{
_myText = theTextBox.Text;
OnPropertyChanged("MyText");
}
}
[ValueConversion(typeof(string), typeof(System.Windows.Visibility))]
public class StringToVisibilityConverter : System.Windows.Data.IValueConverter
{
public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
System.Windows.Visibility vis;
string stringVal = (string)value;
vis = (stringVal.Length < 1) ? Visibility.Visible : Visibility.Hidden;
return vis;
}
public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return null;
}
}
In the XAML:
<TextBlock Background="AliceBlue" >
<TextBlock.Visibility>
<Binding ElementName="window1" Path="MyText" Converter="{StaticResource stringToVisibilityConverter}"/>
</TextBlock.Visibility>
</TextBlock>