C#访问运行时创建的控件

问题描述 投票:0回答:1

我是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             
    }
}
c# wpf wpf-controls
1个回答
0
投票

最简单的方法是在字段中存储引用:

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"; 
    }
}

如果要存储多个控件,请使用字典或列表。

© www.soinside.com 2019 - 2024. All rights reserved.