Accessing XAML Controls from C # Code

I have two files in my VS project: Custom.xaml and Custom.cs

In my XAML file, I have the following text fields:

 <TextBox x:Name="TextBox1" Text="{Binding Value, Mode=TwoWay}" Foreground="Black" Background="Green" SelectionChanged="TextBox1_SelectionChanged" /> <TextBox x:Name="TextBox2" Text="{Binding Value, Mode=TwoWay}" Foreground="Black" Background="Green" SelectionChanged="TextBox2_SelectionChanged" /> 

In my .cs, I have the following method:

  void TextBox1_SelectionChanged(object sender, RoutedEventArgs e) { TextBox t = e.Source as TextBox } 

I can successfully remove the event handler above. Then I can capture TextBox1 and its properties using e.Source , but I would like to access TextBox2 and its properties.

Like sidenote, a .cs file is just the C# class I am referring to, not xaml.cs. In addition, I understand that I can implement this using UserControl, but I cannot do this in this scenario for reasons beyond the scope of this publication.

Please advise how I can get / set TextBox2 properties.

Thanks.

EDIT: Any other input? As a workaround, I added a TextBox2_Loaded event handler, and then set e.Source to the instance variable. Then in TextBox1_SelectionChanged I can access the instance variable. I'd love to just set up direct control (for example, TextBox2.IsEnabled). I have to skip somewhere declaration or inheritance. Cannot find the control using FindName.

+6
source share
3 answers

Ok, so I apparently left a critical component in this post ... My TextBox controls are inside the DataTemplate controls. From my research, TextBox controls are not available if inside the DataTemplate controls. I really didn’t think this mattered, but I think that instance variables are not created when this script exists.

If I interpret this incorrectly, enter input. For now, I went ahead and added the Loaded event and defined the TextBox controls as instance variables so that I could access them and change properties when other actions happen.

Thank you all for your input.

+3
source

As long as you set the name in XAML, you can access it directly by name (the XAML compiler will create an instance variable for you.)

 void TextBox1_SelectionChanged(object sender, RoutedEventArgs e) { TextBox t = e.Source as TextBox TextBox2.Text = "Whatever"; } 
+3
source

It happened to me. I had to close my decision and reopen it.

0
source

Source: https://habr.com/ru/post/909897/


All Articles