Josh
Josh

Reputation: 3611

Access XAML controls from C# code-behind

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

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

<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 hit the event handler above. Then, I can grab TextBox1 and it's properties by using e.Source, but I would like to access TextBox2 and it's properties.

As a sidenote, the .cs file is just a C# class that I am referencing, not a xaml.cs. Additionally, I understand that I could implement this via a UserControl, but cannot do that in this scenario for reasons that are outside the scope of this post.

Please advise on how I can get/set properties of TextBox2.

Thanks.

EDIT: Any other input on this? As a workaround, I've added an event handler called TextBox2_Loaded, and then set e.Source to an instance variable. Then, in TextBox1_SelectionChanged, I can access the instance variable. Would really like to just target the control directly (ex. TextBox2.IsEnabled). I must be missing a declaration or inheritance somewhere. Can't even find the control using FindName.

Upvotes: 7

Views: 13432

Answers (3)

flux
flux

Reputation: 1638

This just happened to me. I had to close my solution and reopen it.

Upvotes: 1

Josh
Josh

Reputation: 3611

Alright, so I apparently had left out a critical component in this post... My TextBox controls are inside of DataTemplate controls. From my research, the TextBox controls cannot be accessed when inside of DataTemplate controls. I really didn't think that would matter, but I guess the instance variables are not created when this scenario exists.

If I've interpreted this incorrectly, please provide input. For now, I've gone ahead and added a Loaded event and defined my TextBox controls as instance variables so that I can access them and change properties when other activities occur.

Thanks for everyone's input.

Upvotes: 4

GazTheDestroyer
GazTheDestroyer

Reputation: 21241

As long as you have set a namein the 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";
} 

Upvotes: 3

Related Questions