Accessing XAML objects in Code Behind.

Here i am explaining how to access XAML Objects in Code Behind.


Inorder to access XAML objects in code behind you need to define them with the same name as given in the XAML document.

For example in the below source code i named the object as objText and the object is defined with the same name in the code behind:

<body >

Here i took 1 textBlock,1 Button control on to the form.If we place mouse pointer in textBlock or in button control then text for button control will be changed.

If we remove the mouse pointer from textblock or from Button control again text for button control will be changed.
</body >

<h3 >Source Code:</h3 >

<Window x:Class="AccessingXAMLObjsInCodeBehind.Window1"
Title="Window1" Height="300" Width="300" >
<Grid >
<Canvas MouseEnter="ChangeValueEnter" MouseLeave="ChangeValueLeave" >
<TextBlock Name="ObjText" Height="22" Canvas.Top="26" Canvas.Left="71" Width="146" >
Place your Mouse Here...!
</TextBlock >
<Button Canvas.Left="51" Canvas.Top="86" Height="23" Name="button1" Width="181" >Button</Button >
</Canvas >
</Grid >
</Window >

<h3 >Code :</h3 >

namespace AccessingXAMLObjsInCodeBehind
/// <summary >
/// Interaction logic for Window1.xaml
/// </summary >
public partial class Window1 : Window
public Window1()
ObjText = new TextBlock();
private void ChangeValueEnter(object sender,EventArgs e)
button1.Content = "Mouse Entering.";
private void ChangeValueLeave(object sender, EventArgs e)
button1.Content= "Mouse Leaving.";

Build the Project.

Then execute the project by pressing F5.

Thank you.


  • Accessing XAML objects in Code Behind. (39425-4027-AccessingXAMLObjsInCodeBehind.rar)
  • Comments

    No responses found. Be the first to comment...

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: