29 Jan

How to Programmatically access Constants declared in your Xaml

comments

If you have been looking out for a way to declare some constants in your xaml and then programmatically access them, then here’s a way I follow.

Open your App.xaml and add the following string constant to it

<Application    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"    x:Class="SampleSilverlight.App"    xmlns:clr="clr-namespace:System;assembly=mscorlib">    <Application.Resources>        <clr:String x:Key="DC">DevCurry</clr:String>    </Application.Resources></Application>

We will access this string constant programmatically using C# or VB.NET. 
Open your Page.xaml and add a TextBlock and a Button to it.
<StackPanel Height="200" Width="200">   <TextBlock x:Name="tb"></TextBlock>    <Button x:Name="btnFetch" Content="Fetch"            Click="btnFetch_Click"></Button></StackPanel>
Now add the following code on button click:
C# 
private void btnFetch_Click(object sender, RoutedEventArgs e){    if (Application.Current.Resources.Contains("DC"))    {        tb.Text = (string)Application.Current.Resources["DC"];    }}
VB.NET
Private Sub btnFetch_Click(ByVal sen As Object, ByVal e As RoutedEventArgs)    If Application.Current.Resources.Contains("DC") Then       tb.Text = CStr(Application.Current.Resources("DC"))    End IfEnd Sub

The Application.Resources gets a collection of Application-Scoped resources.

On clicking the button, the text ‘DevCurry’ gets displayed

image

Share:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • DZone
  • LinkedIn
  • Reddit
  • StumbleUpon
  • Twitthis

From DevCurry

Leave a Reply

Spam Protection by WP-SpamFree

Categories