How to Programmatically access Constants declared in your Xaml

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 If
End Sub

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

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


image

1 comment:

  1. Thanks man, I was getting crazy and dont know whatever to know how to read the XAML contents and when I saw your post, I said "May GOD (Allah) gives you long life.

    BIG THANKS.

    -Danish Sami.

    ReplyDelete