我是C#和WPF的新手。如果在XAML中创建控件,则可以在代码中的任何位置访问其属性。但是,如果我在运行时创建控件,则当我尝试在其创建方法之外访问它时,该控件显示为null。
公共局部类MainWindow:Window{
public MainWindow()
{
InitializeComponent();
Button newBtn = new Button();
newBtn.Content = "Test";
newBtn.Name = "btnTest";
spTest.Children.Add(newBtn);
}
private void WPFButton_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
//I want to access the button called btnTest and display the name of the button
}
}
最简单的方法是在字段中存储引用:
public partial class MainWindow : Window
{
private Button _newBtn;
public MainWindow()
{
InitializeComponent();
_newBtn = new Button();
_newBtn.Content = "Test";
_newBtn.Name = "btnTest"; // < the name is not needed, because you already have a reference. (so you don't have to use FindControl)
spTest.Children.Add(_newBtn);
}
private void WPFButton_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
//I want to access the button called btnTest and display the name of the button
_newBtn.Content = "Test2";
}
}
如果要存储多个控件,请使用字典或列表。