简体   繁体   中英

How to find XAML Controls with FrameworkElement.FindName(String) Method?

My MainWindows.xaml contains this.

<TextBox AutomationProperties.Name="LinkDrive TextBox" x:Name="MyName"/>

Then I'm wanting in the MainWindows.xaml.cs to modify the TextBox.Text property.

So I have to find the right element. I don't know if this is the proper way. ♂️ FrameworkElement.FindName(String) Method

public sealed partial class MainWindow :Window {
   public MainWindow() {
      this.InitializeComponent();
   }

   private void btn_click(object sender, RoutedEventArgs e) {
     // I think I have to go here with somethink like this?
     // this.Current.MainWindow.FindName("MyName");
   }
}

If you define the x:Name in your XAML, then you can directly access the named element from inside the methods of your code-behind.

   private void btn_click(object sender, RoutedEventArgs e) {
     // Just call the named element directly here.
     MyName.Text = "Hello";
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM