This question already has an answer here:
How to add a materialDesign:Hint to a TextBox in code
(1 answer)
Closed 8 days ago.
So I have this xaml line in my WPF project:
<PasswordBox x:Name="passwd" materialDesign:HintAssist.HelperText=""
materialDesign:HintAssist.Hint="Password" materialDesign:HintAssist.Background="#1A1F25"
materialDesign:HintAssist.Foreground="White" Padding="10" Margin="0 0 0 20"/>
And by clicking a button, my C# code has to check if the password is inputed correctly, otherwise it has to change HelperText into "Wrong".
I have tried smth like this, but without any succes:
else if (user_password.Password.Length > 32 || user_password.Password.Length < 10)
{
MaterialDesignThemes.Wpf.HintAssist.HelperTextProperty = "Wrong!";
}
The HelperText property of HintAssist is not a static property, so you can't change it like that. Insted of that you should use SetHelperText method for your PasswordBox which you can find by name:
// if user_password is not an isntance of PasswordBox then you need to retrieve it first
if (passwordBox.Password.Length > 32 || passwordBox.Password.Length < 10)
{
MaterialDesignThemes.Wpf.HintAssist.SetHelperText(user_password, "Wrong!");
}
Related
This question already has answers here:
How do I get a TextBox to only accept numeric input in WPF?
(33 answers)
Closed 2 years ago.
i have tried looking for some scources on how to make the user only enter numbers instead of letters. i want to display a message on that so the user knows they need to type in a number. i would like some pointers on how to impliment that condition.
(this is done in WPF c# visual studio)
private void Add_Click(object sender, RoutedEventArgs e)
{
//text box
number1 = Convert.ToInt32(TextBox1.Text);
number2 = Convert.ToInt32(TextBox2.Text);
//if number1 and number2 are less than 1
if (number1 < 1 || number2 < 1|| number1 > 100 || number2 > 100)
{
MessageBox.Show("INVALID INPUT");
TextBox1.Text = " ";
TextBox2.Text = " ";
}
else if (!success)
{
MessageBox.Show("Type a number please.");
success = int.TryParse(TextBox1.Text, out number1);
success = int.TryParse(TextBox2.Text, out number2);
}
//operation
answer = number1 + number2;
//
//when clicked
answerText.Text = answer.ToString();
}`
You are going about it the wrong way. In WPF, you can do "binding" to a public getter/setter of a given type. The framework itself does the converting and allows proper value or not without you having to try and parse it.
For example, in your code-behind (.cs portion), create a public property for what you are using for input. Ex:
// This is a public getter/setter for binding and defaults its value to 27.
public int MyTextInput {get; set; } = 27;
The only reason I am setting the default to 27 is so when you get the binding done and run the form, you know it is working properly if the form shows 27 when initially displayed. If not, then your binding / data context is not correct and have to fix that part first. But once its done, you should be good and can change the default back to 0.
Then, in the single textbox on the form wide enough to show 2 digits, set the binding to this property something like (you may need to specify a grid row/column if your form is so established with a grid for alignment).
<TextBox Text="{Binding MyTextInput}" MaxLength="2" />
Now, when you run the form, the textbox control will be "bound" to your class's public property "MyTextInput" as an integer data type. If you try to put in charaacters, wpf will automatically show the box with a red border indicating an invalid value.
Then, in whatever your click / button handler is, you can just look at the "MyTextInput" value and go accordingly.
Obviously if you have multiple actual values you are expecting, just create two public properties and two textbox entries each bound to a respective public property you make available.
This question already has answers here:
Making an indexed control array?
(7 answers)
Closed 3 years ago.
I am new with C# and trying to iterate values of 4 textboxes on my winform application, before i look into list arrays, is it possible to loop all 4 of the textboxes appending the index number?
Example
for(i =0; i == 4; i++){
textBox_+ i +.Text
}
Certainly, though you do it slightly differently. You need to iterate over the Control collection and search for your textboxes.
E.g.
foreach (var textBox in this.Controls.OfType<TextBox>())
{
textBox.Text = "bla";
}
If you want to access only certain textboxes - you could tag them via Tag property and search only for those. E.g.
foreach (var textBox in this.Controls.OfType<TextBox>())
{
if (textBox.Tag == "sometag")
textBox.Text = "bla";
}
This question already has answers here:
Get a Windows Forms control by name in C#
(14 answers)
Closed 3 years ago.
We are supposed to code Conway's Game Of Life in a C# Winform application. So, I created a 10 by 10 "game board" out of buttons. Pink means dead, blue means alive. And for ease of access, each button is named after its coordinates on the game board (e.g. x1y1, x10y9, x5y5). But then I realized I have no idea how to loop through 100 form controls and perform do stuff to each individual according to their color/value. In HTML/Javascript, I used the following loop:
for(row = 1; row <= 10; row++){
board[row] = new Array(10); //creates a 10 by 10 matrix to store the board's values in it.
for(col = 1; col <= 10; col++){
var position = "x" + row + "y" + col;
var val = parseInt(document.board.elements[position].value);
board[row][col] = val;
}
}
So the question is this: Is there a way to call form controls through strings not variable names? Something like Form1.getControlByName(string) or something?
You could set the Name property of each Button control you create. E.g. let that button is a reference to a Button control:
button.Name = "11";
Then you could use Control.ControlCollection.Find method to find the button control you are looking for as below:
Button button = this.Controls.Find("11", true).FirstOrDefault() as Button;
The this is a reference to the Form instance. You need to call FirstOrDefault, since Find returns an array of the Controls, whose name is "11". Last you have to use the as operator to convert the Control object to a Button. If conversion fails the value of button is null. So after this conversion you have to check if it is not null:
if(button != null)
{
// place here your code
}
I'm writing a little WPF Apllication where I track some Items. There are a total of 30+ Items, that can be tracked, but none of them have to. This is reflected in a List I populate in the settings section (the TrackedItems object below).
There is a total of 10 Stackpanels I use to display the items. I've made a Collection for them for easier access (StackedpanelsForTrackedItems)
The User has the Option to reduce the panels that are displayed to 3, 5 or 10 (Preferences.NumberNodesDisplayed contains that number) to reduce clutter. So regardless of how many items are tracked, there should never be more SPs visible than this option allows.
Also the application should recognize if the amount of items, that are currently tracked is fewer than the currently selected option.
For example, if i currently only track 6 items, but option is set to 10, it should only display the first 6 SPs regardless.
I came up with this logic:
Collection<UIElement> StackpanelsForTrackedItems = new Collection<UIElement>();
foreach (UIElement element in StackpanelItemParent.Children)
{
if (element is StackPanel)
{
StackPanel sp = (StackPanel)element;
StackpanelsForTrackedItems.Add(sp);
}
}
int i = 0;
foreach (UIElement item in StackpanelsForTrackedItems)
{
if ((i < TrackedItems.Count) && (i < Preferences.NumberNodesDisplayed))
item.Visibility = Visibility.Visible;
else
item.Visibility = Visibility.Collapsed;
i++;
}
Now if i select lets say 6 Items (which means TrackedItems.Count = 6) and I choose 10 Items to be displayed at maximum (which means Preferences.NumberNodesDisplayed = 10) it should still set the visibility of
StackpanelsForTrackedItems[6] to StackpanelsForTrackedItems[9] at 'collapsed', but it doesnt, it always displays every 10 SPs.
How can the if-statement be true if (i < TrackedItems.Count) is already false?
I think I have a major flaw in my logic, but I cant for my life find it.
Help please :)
Edit: as requested
<StackPanel x:Name="StackpanelItemParent" Orientation="Vertical">
<StackPanel x:Name="StackpanelItem1" Orientation="Horizontal">
// stuff here...
</StackPanel>
<StackPanel x:Name="StackpanelItem2" Orientation="Horizontal">
//stuff here...
</StackPanel>
<StackPanel x:Name="StackpanelItem3" Orientation="Horizontal">
// stuff here...
</StackPanel>
<StackPanel x:Name="StackpanelItem4" Orientation="Horizontal">
// stuff here...
</StackPanel>
<StackPanel x:Name="StackpanelItem5" Orientation="Horizontal">
// stuff here...
</StackPanel>
//
//
//
<StackPanel x:Name="StackpanelItem10" Orientation="Horizontal">
// stuff here...
</StackPanel>
</StackPanel>
The Collection gets populated correctly when i debug
StackpanelsForTrackedItems[0] would be StackpanelItem1
StackpanelsForTrackedItems[1] would be StackpanelItem2
StackpanelsForTrackedItems[2] would be StackpanelItem3 etc.
I see no error there :-/
EDIT2:
I found the error,and I'm just too dumb I guess
when I ran the app without breakpoints and changed the items to track, this behaviour above occured
so i went ahead an set breakpoints to track down all variables, this however prevented my app to execute the method, where the TrackedItems object gets populated again...
a simple TrackedItems.Clear() fixed everything, obviously once the method is called again later, there would be 12 items in that list and not 6 anymore
i feel really embarrased for asking the question now :(
at least I managed to track it down on my own, and I learned a thing or two from the comments, so it wasnt completely wasted I guess
thanks everybody for trying to help though, much appreciated!
I have simulated the logic into a list of Booleans. True means to be shown while false means hidden.
The following the user has selected 10 items to be tracked but six only exist:
var StackpanelsForTrackedItems = Enumerable.Range(0, 10)
.Select (e => true)
.ToList();
int tracked = 6;
int max = 10;
StackpanelsForTrackedItems.Select ((sp, index) => sp = (index < max) && (index < tracked));
Result:
For
int tracked = 6;
int max = 3;
Result
For the WPF visibility change
.Select ((sp, index) => sp.Visibility =
((index < max) && (index < tracked)) ? Visibility.Visible
: Visibility.Collapsed);
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to select text from the RichTextBox and then color it?
I don't really have any code to show, because I don't know :(. I have a server that outputs information with tags. For example:
15:44 [INFO] Loaded Properties
15:45 [ERROR] Properties not found
How do I look in the richtextbox and make all ERROR tags red, INFO tags GREEN, etc.?
I think this should do what you want:
for(int i=0; i<rtb.Lines.Length; i++)
{
string text = rtb.Lines[i];
rtb.Select(rtb.GetFirstCharIndexFromLine(i), text.Length);
rtb.SelectionColor = colorForLine(text);
}
private Color colorForLine(string line)
{
if(line.Contains("[INFO]", StringComparison.InvariantCultureIgnoreCase) return Color.Green;
if(line.Contains("[ERROR]", StringComparison.InvariantCultureIgnoreCase) return Color.Red;
return Color.Black;
}
Edit: Changed StartsWith to Contains
You can do something like:
//will select characters form index 0 to 9
richTextBox1.Select(0, 10);
//will set the characters from 0 to 9 to red
richTextBox1.SelectionColor = Color.Red;