Saturday 31 March 2012

ObjectDataProvider In Wpf:-


We can get the objects in to the xaml by using ObjectDataProvider.We can aslo  call the functions from the xaml.

->Create a customer class with properties FirstName,LastName and create a      GetCustomer function which is called by the xaml.
   public class Customer
    {
        public string FirstName { get; set; }

        public string LastName { get; set; }

        public Customer GetCustomer()
        {
            return new Customer { FirstName = "Jim", LastName = "Smith" };
        }
    }

->Add the ObjectDataProvider in the xaml as static resource.
<Window x:Class="WpfCodeObjectToXaml.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfCodeObjectToXaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.Resources>
            <!--Here specify the type of object and method name-->
            <ObjectDataProvider x:Key="odpCustomer" ObjectType="{x:Type local:Customer}" MethodName="GetCustomer"></ObjectDataProvider>
        </Grid.Resources>
        <!--Here we set the datacontext of stack panel to the object data provicer-->
        <StackPanel DataContext="{StaticResource odpCustomer}">
            <!--Bind the first name-->
            <TextBlock Text="{Binding Path=FirstName}"></TextBlock>

            <!--Bind the last name-->
            <TextBlock Text="{Binding Path=LastName}"></TextBlock>
        </StackPanel>
    </Grid>
</Window>

Let me know, if you have any feedback. Mail me for source code. Enjoy reading my articles…
sekhartechblog@gmail.com

No comments:

Post a Comment