It's possible convert string into Label name? [duplicate] - c#

This question already has answers here:
Find control by name from Windows Forms controls
(3 answers)
Closed 4 years ago.
Using C# and Windows Forms, i would like to use the name of a Label as a parameter of another function, like this:
startBox(label_box, "11", Color.Red);
Definition of startBox:
private void startBox(Label label, string text, Color color) {
label.BackColor = color;
label.Visible = true;
label.Enabled = true;
label.Text = text;
}
But, is there any way to convert an string to the name of a Label?
In my case, label_box is a string.
ps¹. I need to do this because i have N Labels and the name is should be typed by the user.
ps². To Invoke a method using a string i used the MethodInfo.
EDIT: The solution using Controls does not apply. In my case, a string is given as an input, if the string is the name of one of the labels the function is called.
Thank you, and sorry for the spelling flaws in English.

so you want to be able to operate on a label, where the name of the label is supplied as input. I would do this with a dictions
var lDict = new Dictionary<string, Label>();
lDict["l1"] = Label1;
lDict["l2"] = Label2;
....
then
void Func(string labelName)
{
var label = lDict[labelName];
label.Visible = true;
...
}
you could do all sorts of complicated reflection tings but that feels like overkill

Related

In WPF, how do I change the source of an image programatically? [duplicate]

This question already has answers here:
How to load image to WPF in runtime?
(2 answers)
Closed 1 year ago.
I have a custom control with a default image that I want to change based on which iteration of the control it is. For example, I have one for "F1" and "NumLock" and so on. In the constructor of the control, I have this:
public FixerBox(Dictionary<string,string> deets)
{
InitializeComponent();
btnOff();
this.FixerTitle.Text = deets["Title"];
this.FixerDesc.Text = deets["Description"];
this.FixerTags.Text = deets["Tags"];
this.FixerImg.Source = new BitmapImage(new Uri(deets["Img"], UriKind.Relative));
}
The bitmap stuff was based on another answer and produces this:
Below is the control itself showing that it's correctly getting the title, tags, and description, but the image is bunk (on the left side, that thin grey line is the border that should be around the image).c#
If I was using HTML/CSS, I could right-click the image to see what exactly its properties are, but I don't know how to get that kind of information using WPF. The best I could manage was in the top area is a status window where I've manually printed a "Tostring" output of the first controls image source data. Near as I can tell, it's all correct, but there's no actual image there. Every subsequent control has the same output (one thin line where the image should be).
EDIT Per comments, here is some more of the information. The main XAML file loads up the controls like so in its constructor:
public partial class MainWindow : Window
{
private Fixers fixers = new Fixers();
// This is the custom control consisting mostly of various boxes
private Dictionary<string,FixerBox> fixerBoxes = new Dictionary<string, FixerBox> { };
public MainWindow()
{
InitializeComponent();
var fixNames = fixers.FixerNames();
foreach (string key in fixNames)
{
fixerBoxes[key] = new FixerBox(fixers.GetFix(key));
FixersArea.Children.Add(fixerBoxes[key]);
}
StatusBox.Text += fixerBoxes["F1"].FixerImg.Source.ToString();
}
}
The fixers variable is of class Fixers which consists of the below (abbreviated to show just the F1 function for brevity):
class Fixers
{
private string ClearWS(string str)
{
var first = str.Replace(System.Environment.NewLine, "");
return first.Replace("\t", "");
}
// Loads registry functions
private Regis regStuff = new Regis();
// Loads preferences from the file
private Prefs prefs = new Prefs();
// A timer to make sure the system behaves
private Timer watcher;
// Watcher action toggles
private bool watchNumL = false;
// Translation array from fix shortname to various data about them
private Dictionary<string, Dictionary<string, string>> fixers = new Dictionary<string, Dictionary<string, string>>
{
["F1"] = new Dictionary<string,string> {
["PrefName"] = "KillF1UnhelpfulHelp",
["Img"] = #"/graphics/F1key.png",
["Title"] = #"Diable F1 ""Help"" function",
["Description"] = #"
Have you ever hit the F1 key by accident and had a distracting and unhelpful window or webpage open as a result?
Windows set the F1 key to a generic help function that basically never helps and always gets in the way.
Enable this control to disable that obnoxious design choice. Note that some programs still respond to F1 on their own accord,
but this will stop the default Windows behavior in things like Windows Explorer at least.
",
["Tags"] = "#Keyboard,#Rage"
},
};
public Fixers()
{
// The readability hack above with multi-line strings introduces a bunch of extra whitespace. Let's clear that out
foreach (var fixKey in fixers.Keys)
{
fixers[fixKey]["Description"] = ClearWS(fixers[fixKey]["Description"]);
}
}
public List<string> FixerNames()
{
return fixers.Keys.ToList();
}
public bool IsFixed(string which)
{
// If we're watching, it's fixed
if ("NumL" == which) return watchNumL;
// For anything registry related
return regStuff.IsFixed(which);
}
public Dictionary<string,string> GetFix(string which)
{
return fixers[which];
}
}
if you use binding, you can create in your ViewModel a string, in which is stored the path of your image, then you can easily change programatically its path.
Then in XAML just bind image's source to the string.
In my case I have a list of objects, with the property `ImageName' :
<Image Source="{Binding DataContext.SelectedMacro.ImageName,
RelativeSource={RelativeSource AncestorType=Window}}"/>

c# How to pass label to an anonymous form [duplicate]

This question already has answers here:
Bind a label to a "variable"
(4 answers)
Closed 3 years ago.
I want to pass my Label I use in my mainForm to an anonymous form. By anonymous form I mean this form count can be infinite. I will show my code to make it clear.
This is my second form.
LABEL sourceObj;
public frmCounters(string text, ref LABEL _sourceObj)
{
InitializeComponent();
sourceObj = _sourceObj;
this.Text = text;
this.lblInfo.Text = text;
this.lblTime = sourceObj;
}
and this is how I call it
AnonymForm afrm = new AnonymForm("TEST1", ref lblTEST1);
afrm.Show();
all I want to achieve here is update anonyform's label whenever I change the source from my main form. I have tried with and without ref keyword in constructor. I've bind the value I get in constructor to another variable I hold in anonymform. I also wanted to try send text property as reference but Visual Studio said I can't pass properties with ref keyword.
My question is how can I achieve that?
Add to AnonymForm class method like:
public void SetLabelText(string value)
{
this.label.Text = value;
}
And call it from main form:
afrm.SetLabelText("TEXT");

C# Load TextBlock content from a valriable (containing images)

I just wrote some nice functions, that allow me to add Emojis in a textbox with Inline.Add([Syste.Windows.Controls.Image]). It basically takes a TextBlock as an argument and appends the text/emojis that I want.
Icons is a Dictionary which maps from string to BitmapImage. (unable to use '<' and '>' here somehow)
private void AddTextToString(TextBlock block, string txt)
{
var textRun = new Run(txt);
textRun.BaselineAlignment = BaselineAlignment.Center;
block.Inlines.Add(textRun);
}
private void AddEmojiToString(TextBlock block, string txt)
{
if (!Icons.ContainsKey(txt))
return;
System.Windows.Controls.Image emo = new System.Windows.Controls.Image();
emo.Height = 15;
emo.Width = 15;
emo.VerticalAlignment = VerticalAlignment.Center;
emo.Source = Icons[txt];
block.Inlines.Add(emo);
}
Now I was wondering if there was an elegant way of saving this kind of text to a variable, so that I could bind the TextBlock Text dynamically to it.
Thank you very much in advance!
TextBlock.Inlines is property of type InlineCollection, you can use this type to keep the contents.

Change Textbox text from another frame(container)

I see here lot of similar question, but I still not find answer that help me in situation.
I have two frame(lets say FrameChild), one is "in" another(practically FrameChild is in this frame, lets say FrameMain).
When I insert all parameters in FrameChild and tap on button witch is on bottom of FrameMain I call method that return string...
Now when i get string i need to change textbox text in FrameChild
I have tray many way.
First idea was something like:
FrameChild frm = new FrameChild;
frm.textbox.text = "somestring";
But nothing happen.
Than i thing use some property.
in FrameChield:
public string setTicNo
{
set
{
textBox.Text = value;
}
}
in FrameMain:
FrameChild frm = new FrameChild;
frm.setTicNo = "somestring";
When i debbuging I get value, but textbox still is empty...
On the end I try to bind textbox text on setTicNo;
public string setTicNo
{
get
{
return setTicNo;
}
set
{
setTicNo = value;
}
}
Xaml:
Text = {Binding setTicNo, Mode=TwoWay,UpdateSourceTrigger=Explicit}
(here i try use more bindings, but every time i get infinite loop.
Please help , I not have more ideas..
Thanx
Did you try building a single view model and bind it to both frames, if it was passed by ref which is the default it will change the value once you do.
A side note implement a INOTIFYPROPERTYCGANGED in the View model

Declaring a new object via variable name

I'm fairly new to C# (and programming in general) so stick with me if I make any huge errors or talk complete bull.
So what I'm trying to do is have a private void that resizes the background image of a button. I send the name of the button to the private void via a string. Anyway, the code looks something like this:
ButtonResize("Zwaard");
protected void ButtonResize(string Button)
{
string ButNaam = "btn" + Button;
Button Butnaam = new Button();
Butnaam.Text = ButNaam;
if (Butnaam.BackgroundImage == null)
{
return;
}
else
{
var bm = new Bitmap(Butnaam.BackgroundImage, new Size(Butnaam.Width, Butnaam.Height));
Butnaam.BackgroundImage = bm;
}
}
But it doesn't work like that. I can't seem to find a way to declare a new object named the value I have in a string. What I want my code to do is instead of making a button called "Butnaam", I want it to create a button called btnZwaard (the value of the string Butnaam).
How do I tell C# I want the value of the variable to be the name of a new button, not literally what I type?
Thanks in advance.
Are you looking for something like this? By passing the Button to the method you can then act on the object. If this is what you are looking for then you should read Passing Reference-Type Parameters
protected void ButtonResize(Button button)
{
if (button != null && button.BackgroundImage != null)
{
button.BackgroundImage = new Bitmap(button.BackgroundImage, new Size(newWidth, newHeight));
}
}
A string is a piece of text. You subsequently refer to it as a class, which is wrong. Assuming it were right you create a new button rather than "resize its image".
What you want to do to get you started is create a new function in the same class as the dialog that has the button. That function can resize the image of the control.
Edit: this doesn't seem like a good starting point for learning a language, btw. Please find a good online tutorial for starting in C# (e.g. a hello world application).

Categories