Relative noob here coming from Python trying to build a UWP app in c# and XAML.
The short version: How do I refer to a button using its string 'Name' to change its color. It seems that if I have given it a name I should be able to refer to it by its name, something like:
"navBtn5".Background = myColor;
//or
navBtn5.Background = myColor;
I have looked all over, the best I found was this from here on stackOverflow: How to control a xaml button from C# in WPF
which looks exactly like what I want. However this does not work, will not even build as I just get told:
Error CS0103 The name 'navBtn5' does not exist in the current context
This could be because I am using UWP and that is for WPF.
The long Version: My app is creating the navigation menu by data binding to a List that is put together in a separate class. I am creating a type of MenuButton in my class then returning a list of them. This is a stripped down version of my class:
class MenuButton{
public string buttonName { get; set; }
public string buttonContentText { get; set; }
public int buttonWidth { get; set; }
public int buttonHeight { get; set; }
public List<byte> buttonColor { get; set; }
}
class menuButtonManager{
public static List<MenuButton> getButtons(){
var menuButtons = new List<MenuButton>();
menuButtons.Add(new MenuButton{
buttonName = "navBtn1",
buttonWidth = 50,
buttonHeight = 50,
buttonContentText = "\uE173",
buttonColor = new List<byte> { 255, 82, 190, 128 },
});
menuButtons.Add(new MenuButton{
buttonName = "navBtn2",
//and so on
});
menuButtons.Add(new MenuButton{
//and so on
});
}
return menuButtons;
}
At Run Time, when the user clicks a button I want to loop through all the buttons in the List and change their color to grey if it was not that one that was clicked, green if it was the clicked button. something like this:
private void navClick(object sender, RoutedEventArgs e){
//who called me
string senderName = ((Button)sender).Name;
foreach(MenuButton m in menuButtons){
if(m.buttonName == senderName){
Button senderButton = (Button)sender;
senderButton.Background = myFunkyColor;
// I can already do this as I already have
// the sender cast to a button
}
else{
// change button to grey
// This is where I am stuck
// I know m.buttonName as a string
// how do I create a usable button object from it?
}
}
}
As you can see I have no trouble changing the properties of the button that was the sender as I have cast it to a type of Button which I can use. The problem for me is when I am acting on a button that is not the sender and all I have is it's string name.