[英]c# WPF How to invoke or call button function using string variable, the string variable contains the button name?
string buttonName="";
private void _1btn_Click(object sender, RoutedEventArgs e){
var button = (Button) sender;
buttonName = button.Name;
ChangeButtonColour();
}
private void ChangeButtonColour() {
buttonName.Background = Brushes.Red;// doesn't Work!
}
我尝试使用字符串变量buttonName(其中包含“_1btn”)调用按钮function,而不是调用实际按钮名称的_1btn。
//find the control by from form element tree
private void ChangeButtonColour(string _btname)
{
Button foundTextBox = FindChild<Button>(Application.Current.MainWindow, _btname);
}
public static T FindChild<T>(DependencyObject parent, string childName)where T : DependencyObject
{
// Confirm parent and childName are valid.
if (parent == null) return null;
T foundChild = null;
int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < childrenCount; i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
// If the child is not of the request child type child
T childType = child as T;
if (childType == null)
{
// recursively drill down the tree
foundChild = FindChild<T>(child, childName);
// If the child is found, break so we do not overwrite the found child.
if (foundChild != null) break;
}
else if (!string.IsNullOrEmpty(childName))
{
var frameworkElement = child as FrameworkElement;
// If the child's name is set for search
if (frameworkElement != null && frameworkElement.Name == childName)
{
// if the child's name is of the request name
foundChild = (T)child;
break;
}
}
else
{
// child element found.
foundChild = (T)child;
break;
}
}
return foundChild;
}
我找到了答案。 您不能将按钮属性存储在字符串变量中。 因此,您创建了一个按钮 object 类型变量,然后将按钮分配给新的按钮类型变量,然后您可以调用按钮属性。
Button buttonName="";
private void _1btn_Click(object sender, RoutedEventArgs e){
buttonName = _1btn;
ChangeButtonColour();
}
private void ChangeButtonColour() {
buttonName.Background = Brushes.Red;// This works!
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.