Access codebehind variable in XAML


How can I access the public variable which in Sample.xaml.cs file like <%=VariableName%>?

4/24/2018 3:56:24 AM

Accepted Answer

There are a few ways to do this.

  • Add your variable as a resource from codebehind:

    myWindow.Resources.Add("myResourceKey", myVariable);

    Then you can access it from XAML:

    <TextBlock Text="{StaticResource myResourceKey}"/>

    If you have to add it after the XAML gets parsed, you can use a DynamicResource above instead of StaticResource.

  • Make the variable a property of something in your XAML. Usually this works through the DataContext:

    myWindow.DataContext = myVariable;


    myWindow.MyProperty = myVariable;

    After this, anything in your XAML can access it through a Binding:

    <TextBlock Text="{Binding Path=PropertyOfMyVariable}"/>


    <TextBlock Text="{Binding ElementName=myWindow, Path=MyProperty}"/>
3/20/2009 4:30:41 PM

For binding, if DataContext is not in use, you can simply add this to the constructor of the code behind:

this.DataContext = this;

Using this, every property in the code becomes accessible to binding:

<TextBlock Text="{Binding PropertyName}"/>

Another way is to just give a name to the root element of the XAML:


Since the XAML is compiled as a partial class of the code-behind, we can access every property by name:

<TextBlock Text="{Binding ElementName="root" Path=PropertyName}"/>

Note: access is only available to properties; not to fields. set; and get; or {Binding Mode = OneWay} are necessary. If OneWay binding is used, the underlying data should implement INotifyPropertyChanged.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow