You can enumerate child controls with VisualTreeHelper
and in the loop you can test :
if (childVisual is Button)
{
((Button)childVisual).Content = "Your text";
}
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
I am making a C# WPF program with 100 buttons.
I want the program to read Settings and change the button names when it is launched.
This is my current code:
public void SetButtonName()
{
Btn_1.Content = Settings.Default.ButtonName[1];
Btn_2.Content = Settings.Default.ButtonName[2];
Btn_3.Content = Settings.Default.ButtonName[3];
.
.
.
Btn_99.Content = Settings.Default.ButtonName[99];
Btn_100.Content = Settings.Default.ButtonName[100];
}
I have a feeling there is a way to make this shorter using loop, but I cannot figure this out after a few days of searching the Internet.
Any help would be really appreciated.
You can enumerate child controls with VisualTreeHelper
and in the loop you can test :
if (childVisual is Button)
{
((Button)childVisual).Content = "Your text";
}
HI,
try following code. stp is the name of StackPanel with Buttons:
public void SetButtonName()
{
foreach (Button item in stp.Children)
if (item.Name.StartsWith("Btn_"))
item.Content= Settings.Default.ButtonName[int.Parse(item.Name.Substring(4))];
}
You could try to see the example below.
public void SetButtonName()
{
foreach (UIElement item in stp.Children)
{
if (item.GetType() == typeof(TextBox))
{
TextBox txt = (TextBox)item;
txt.Text="44";
}
if (item.GetType() == typeof(Button))
{
Button btn = (Button)item;
btn.Content="55";
}
if (item.GetType() == typeof(Rectangle))
{
Rectangle rect = (Rectangle)item;
rect.Fill = new SolidColorBrush(System.Windows.Media.Colors.AliceBlue);
}
}
//item.Content = Settings.Default.ButtonName[int.Parse(item.Name.Substring(4))];
}
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our [documentation][5] to enable e-mail notifications if you want to receive the related email notification for this thread.
[5]: https://learn.microsoft.com/en-us/answers/articles/67444/email-notifications.html