The following steps can be followed to instantiate the object as a resource in XAML.
- Imagine we have a class Person as mentioned below.
Code Snippet
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Data;
- using System.Windows.Documents;
- using System.Windows.Input;
- using System.Windows.Media;
- using System.Windows.Media.Imaging;
- using System.Windows.Navigation;
- using System.Windows.Shapes;
- using System.ComponentModel;
- namespace DataBinding_Source_Property
- {
- /// <summary>
- /// Interaction logic for MainWindow.xaml
- /// </summary>
- public partial class MainWindow : Window
- {
- public MainWindow()
- {
- InitializeComponent();
- }
- }
- public class Person
- {
- private string fullname;
- public string FullName
- {
- get
- {
- return fullname;
- }
- set
- {
- fullname = value;
- }
- }
- }
- }
Steps to be followed are:
- Include the namespace of the class as shown in line5. Notice that it is assigned to xmlns:kishore. Here we are using name resolution kishore with XML namespace. It can be xmlns:local or xmln:src or any other word followed by xmlns:. We have to use the same identifier(kishore or local or src) when we refer (or when want to use) the namespace.
- <Window x:Class="DataBinding_Source_Property.MainWindow"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- Title="MainWindow" Height="350" Width="525"
- xmlns:kishore="clr-namespace:DataBinding_Source_Property">
- To use the classes in the above namespace, we need to create an object of the class we are interested in as shown below. Ex, Person class
<Window.Resources>
<kishore:Person x:Key="PersonXAMLDataSource" FullName="Kishore1021"/>
</Window.Resources>
- Once the object of the Person class is instantiated, you can use it as a source during binding operation to bind to some UI element as shown below.
<TextBox Text="{Binding Source={StaticResource PersonXAMLDataSource}, Path=FullName}"></TextBox>
The complete of the application is as follows.
Code Snippet
- <Window x:Class="DataBinding_Source_Property.MainWindow"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- Title="MainWindow" Height="350" Width="525"
- xmlns:kishore="clr-namespace:DataBinding_Source_Property">
- <Window.Resources>
- <kishore:Person x:Key="PersonXAMLDataSource" FullName="Kishore1021"/>
- </Window.Resources>
- <Grid>
- <Grid.RowDefinitions>
- <RowDefinition Height="*"> </RowDefinition>
- <RowDefinition Height="*"></RowDefinition>
- </Grid.RowDefinitions>
- <TextBox Text="{Binding Source={StaticResource PersonXAMLDataSource}, Path=FullName}"></TextBox>
- </Grid>
- </Window>
Download SourceCode from SkyDrive