简体   繁体   中英

c#, wpf, Dynamically naming controls

How do i create a new Button/Canvas with a dynamic name?

Button {buttonname read from text file} = new Button;

I have googled this for a while now but i can't find the solution.

Thank you!

I'm not sure if I understood correctly, but that name in your example is not the button name, it's just the reference name used in code to access the button. The button name would be set like this:

buttonRefName.Name = "ButtonName1";

So you can set the name to whatever you want: dynamically generated names inside a loop, names read from a file, etc...

You can use the same reference name for multiple buttons, just be sure to add it to List or to WPF Window, Panel, etc... before creating the new one:

var buttonList = new List<Button>();
var buttonRef = new Button { Name = "YourButtonName" };
buttonList.Add(buttonRef);
buttonRef = new Button { Name = "YourButtonName2" };
buttonList.Add(buttonRef);

It not possible the way you want to do it. If you are reading from a text file better use a List or better a Dictionary... an example use is as follows:

var buttons = new Dictionary<string, Button>();
buttons["yourName"] = new Button();
// logic goes here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM