WPF - DatePicker Masked input - c#

I'm developing an WPF application and I got two datepicks input where use
can select the date, But I am having some problem with these inputs cause the user can write whatever they want on it as in the image bellow
Is there some way to mask this inputs ? as dd/mm/yyy to only allow users to write dates and it automatically inserts the / slash ?
I tried follow this example but didn't work as it only formate the date after the user choose it from the calendar
I know that there are some "masked inputs" but they don't work with datepicker input
Thanks in Advance.
EDIT
here is my xaml code
<Border Grid.Column="0" Grid.Row="1" Margin="10 0 0 0" Style="{StaticResource InputBorder}" Height="30" VerticalAlignment="Top">
<DatePicker x:Name="EDT_DATA_INICIAL"></DatePicker>
</Border>
<Border Grid.Column="1" Grid.Row="1" Margin="10 0 10 0" Style="{StaticResource InputBorder}" Height="30" VerticalAlignment="Top">
<DatePicker x:Name="EDT_DATA_FINAL"></DatePicker>
</Border>

Just complementing the #Tronald's answer I'am using his event PreviewTextInput
and I complementend it using this code in a keyUp event
private void SetDateFormat(object sender, KeyEventArgs e)
{
DatePicker dt = (DatePicker)sender;
string justNumbers = new String(dt.Text.Where(Char.IsDigit).ToArray());
if (justNumbers.Length == 8)
{
string newDate = justNumbers.Insert(2, "/").Insert(5, "/");
try
{
dt.SelectedDate = DateTime.Parse(newDate);
}catch(Exception ex)
{
dt.text = "";
}
}
}
That format the date when use only digite numbers or
ex : 18061993 > 18/06/1993 and when the date is incorrect it clears the input preventing errors

Create a PreviewTextInput event in your DatePicker and handle the logic in there. The below example will restrict input to numbers and "/" only. You will have to figure out how to automatically input the "/" on your own if you wish to do that.
Maybe loop through each character of the string as it's built and determine if you need to add the "/" at a certain point. You can e.Handled = true to block the user input then set the DatePicker.Text as required. This should be enough to get you started.
private void DatePicker_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
DatePicker dp = (DatePicker)sender;
Regex regex = new Regex("[^0-9/]"); //regex that matches allowed text
e.Handled = regex.IsMatch(e.Text);
}
Regex reference isSystem.Text.RegularExpressions

Related

When user types invalid characters in textbox1 and in textbox2 an "invalid character message" is appeared and the textbox1's text is made red

I would like to make a fancy invalid character detection , like the one we see in some online websites or mobile applications. I use WPF (.NET Framework) and C# code.
Below is the XAML code of my textbox1 (user input) and textbox2 (invalid character detector).
Note that I use the Material Design themes.
<StackPanel VerticalAlignment="Center" Margin="10,20,10,30">
<TextBox Name="CreatedSQLDatabase"
BorderBrush="Black"
materialDesign:HintAssist.Hint="Add New Database Name"
Style="{StaticResource MaterialDesignFloatingHintTextBox}"
Margin="0,0,0,0"
FontFamily="Champagne & Limousines"
FontSize="12"
MaxLength="25"
KeyDown="OnKeyDownHandler"/>
</StackPanel>
<TextBox Name="InvalidCharacterDetection"
materialDesign:HintAssist.Hint="Invalid character"
Style="{StaticResource MaterialDesignFloatingHintTextBox}"
Margin="10,100,10,40"
FontFamily="Champagne & Limousines"
FontSize="12"
MaxLength="25"
IsReadOnly="True"/>
Below is the C# code of the invalid characters event handler detector :
private void OnKeyDownHandler(object sender, KeyEventArgs e)
{
var regex = new Regex(#"[^a-zA-Z0-9-()/\s\p{IsGreekandCoptic}]");
if (regex.IsMatch(e.Key.ToString()))
{
InvalidCharacterDetection.Text = "You Entered an invalid character";
CreatedSQLDatabase.Foreground = Brushes.Red;
}
else if (String.IsNullOrEmpty(CreatedSQLDatabase.Text))
{
InvalidCharacterDetection.Text = "Database name cannot be empty";
}
else if (CreatedSQLDatabase.Text.Length > 25)
{
InvalidCharacterDetection.Text = "Database name cannot exceed 25 characters";
}
}
The output is not correct (none of the regex expressions is applied):
How could I make the KeyEvent handler to catch the if statements and make the appropriate changes in the color of the textbox1 and the message that is appeared in the textbox2?
Please notify me in the comments if there is any other duplicate question regarding this one. I found the following questions So far :
SO question 1
SO question 2
I don't know about regular expression but I guess you want to check if it doesn't (!) match, don't you? Also, try TextChanged instead of KeyDown and validate the current value of CreatedSQLDatabase.Text:
private void OnTextChanged(object sender, TextChangedEventArgs e)
{
var regex = new Regex(#"...");
if (!regex.IsMatch(CreatedSQLDatabase.Text))
{
InvalidCharacterDetection.Text = "You Entered an invalid character";
CreatedSQLDatabase.Foreground = Brushes.Red;
}
else if (string.IsNullOrEmpty(CreatedSQLDatabase.Text))
{
InvalidCharacterDetection.Text = "Database name cannot be empty";
}
else if (CreatedSQLDatabase.Text.Length > 25)
{
InvalidCharacterDetection.Text = "Database name cannot exceed 25 characters";
}
else
{
CreatedSQLDatabase.Foreground = Brushes.Black;
InvalidCharacterDetection.Text = "The database name is valid";
}
}

Retrieve text from a textbox in visual studio ( windows store app)

In windows store app( express 2013 for windows), i have created a textbox. Now i want to capture or retrieve the text entered by the user for further operations ( specifically, assign the user text to a string).
I tried this :
string input = InputBox.Text;
in the event handler for textbox.But this doesn't seem to work.
Any help is welcome.
<TextBox Text="TextBox"
x:Name="InputBox"
Grid.Row="1"
HorizontalAlignment="Right"
VerticalAlignment="Center"
Width="402"
Height="48"
FontFamily="Arial Black"
FontSize="28"
FontWeight="Bold"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Left" Margin="0,77,0,84"
TextAlignment="Left" TextChanged="InputBox_TextChanged"
/>
C# code follows :
private void InputBox_TextChanged(object sender, TextChangedEventArgs e)
{
string input = InputBox.Text;
}
the problem here is that you´re creating the string inside the event, so it will be erased after the event finish.
what you can do is to create a string inside the form class, and set its value on the text box event.
private string input = string.Empty;
private void InputBox_TextChanged(object sender, TextChangedEventArgs e)
{
input = InputBox.Text;
}
Remove TextChanged="InputBox_TextChanged" from xaml and use InputBox.Text wherever you want to use text of your TextBox.
InputBox_TextChanged will fire on every symbol you type in your textbox, so it is not good idea to get text in text_changed.

windows phone 8 grid checkbox check and uncheck

i have a 100 * 100 grid on one of the page in my app. i have a single checkbox on the top right of the grid.
what i want is that when the user tap or click on the grid first time the checkbox become checked and when i again taps on the grid the checkbox becomes unchecked. how can i achieve it? i am talking about the metro type checkboxes here. or could i use checkbox itself in this manner? is grid the right way to go?
In short i need some guidelines in solving the above problem?
This may work for you
<Grid Height="100" Width="100" Background="Beige" Tap="Grid_Tap" >
</Grid>
<CheckBox x:Name="gridCheckBox" Content="CheckBox" HorizontalAlignment="Left" Margin="369,47,0,0" VerticalAlignment="Top"/>
then for making the checkbox checked and unchecked on the tap event of the grid we need to add the following code
private void Grid_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
if (gridCheckBox.IsChecked == true)
{
gridCheckBox.IsChecked = false;
}
else
{
gridCheckBox.IsChecked = true;
}
}
gridcheckbox.IsChecked = (gridcheckbox.IsChecked == true) ? false : true;

Validate WPF textbox data through XAML [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Validation in textbox in WPF
I am currently using this code to create a numeric only textbox
Xaml
<TextBox Height="22" HorizontalAlignment="Left" Margin="192,118,0,0" Name="Unit_ID" VerticalAlignment="Top" Width="173" PreviewTextInput="UnitID_PreviewTextInput" TextInput="Unit_ID_TextInput" TextChanged="Unit_ID_TextChanged" />
and the C# codebehind
private void UnitID_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
foreach (char c in e.Text)
if (!Char.IsDigit(c))
{
e.Handled = true;
break;
}
is is possible to do this by using XAML EXCLUSIVELY?i am trying to minimize my .cs file
If you bind the value of the TextBox's Text attribute to an int, you'll get a sort of validation, in as much as you won't be able to set the value of MyInt to anything other than an int (and the TextBox border will go red if you try).
In the XAML:
<TextBox Text="{Binding MyInt}"/>
In the presenter:
public class MyPresenter : INotifyPropertyChanged
{
public int MyInt { get; set; }
// ...
}
and set the DataContext of the XAML to an instance of MyPresenter.
Just like you can't use pure HTML to get this done, you can't use XAML exclusively (to my knowledge). I get the whole "less is more" philosophy, but in this case you'll need at least SOME code, e.g. Regex, to validate the input.

WPF, sibling selection like jQuery?

I have the following XAML code as an example in my WPF application
<StackPanel Height="23" Name="MSpanel" Orientation="Horizontal" Width="138" Margin="37,13,0,0" VerticalAlignment="Top" HorizontalAlignment="Left" >
<TextBox Height="23" Name="MTBox" Width="120" Text="0" />
<ScrollBar Height="23" Name="MSBar" Width="18" TouchUp="SBar_TouchUp" />
</StackPanel>
<StackPanel Height="23" Name="CSPanel" Orientation="Horizontal" Width="138" Margin="37,41,0,0" VerticalAlignment="Top" HorizontalAlignment="Left">
<TextBox Height="23" Name="CTBox" Width="120" Text="0" />
<ScrollBar Height="23" Name="CSBar" Width="18" TouchUp="SBar_TouchUp" />
</StackPanel>
I have this function:
private void SBar_TouchUp(object sender, TouchEventArgs e)
{
//what goes here?
//siblings.getFirst('textbox').text += 1;
}
What I was hoping to do, is have 1 function that controls these "Psudo" numeric up downs in WPF. If there was some way to have a unified function that could, reference the sibling textbox, so I only have to write it once. That would be ideal.
I'm very familiar with jQuery, and XAML looks like an HTML DOM, ... Is there a way to browse the tree?
I realize there are existing Numeric Up Downs available to download. This idea I believe would be good to know for the future in other endeavors as well. Thanks.
The solution that worked!
private void SBar_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
if (e.NewValue == 0) return; //abort here, no change
ScrollBar sb = (ScrollBar)sender;
StackPanel sp = (StackPanel)sb.Parent;
TextBox tb = (TextBox)sp.Children[0];
int change = e.NewValue < 0 ? 1 : -1;
sb.Value = 0; //this will invoke this function again
tb.Text = (Convert.ToInt32(tb.Text) + change).ToString();
}
Each element in the visual tree has a Parent and VisualParent property - as all elements are based on UIElement - either should give you the parent object.
In this case the parent of the ScrollBar is the StackPanel. You can then use the Children property of the StackPanel to get the collection of child objects. You know which is the ScrollBar (it's the sender) so the other must be the TextBox.
You can do something like this:
private void SBar_TouchUp(object sender, TouchEventArgs e)
{
//siblings.getFirst('textbox').text += 1;
var siblings = ((sender as FrameworkElement).Parent as Panel).Children;
var textbox = siblings.OfType<TextBox>().First();
textbox.Text = (int.Parse(textbox.Text) + 1).ToString();
}
but I would suspect that there are probably better ways to do what you want, like data binding or naming elements in attached properties.
Yeah, there are many properties for both Logical and Visual trees.
Like FrameworkElement.Parent or Panel.Children.
I don't think there is directly method to get sibling, but its not that hard to get index in list of children of parent and getting next item.

Categories