Bind to Parent Data context property in Data Template Item - Silverlight

Shahvimall
Posted by in Silverlight category on for Beginner level | Points: 250 | Views : 5935 red flag

This article shows how you can bind to a property located in the data context of your parent which is not accessible to the data template item in silverlight, also as silverlight does not fully support 'relative source' is cannot be used.

Introduction


Using parent data context property from the data template item in silverlight

Objective


Bind to the property located in the Data Context of parent control from Data template Item

Using the code


In below image you can see the Update and Delete buttons in the data grid which should be bound to the corresponding commands located in the data context of the containing page.



Below is a data template button which is bound with the 'Edit' command located in the view model of the page,
while the button itself is in the Data Grid bound with a collection as a data context, so button cannot access the 
parent data context property(Edit command).
<sdk:DataGridTemplateColumn>
                        <sdk:DataGridTemplateColumn.CellEditingTemplate>
                            <DataTemplate>
                                <Button Content="Update" Padding="5" Margin="5" Command="{Binding Path=Edit,Source={StaticResource ViewModel}}"  FontSize="11" Height="26" Width="70" ></Button>
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellEditingTemplate>
</sdk:DataGridTemplateColumn>
As you can see in the above code button is bound with the Edit command and the source property is a static view Model, which is the data context of the page.
  xmlns:local="clr-namespace:SilverlightApplication1"
    mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480"
    Title="About" 
    Style="{StaticResource PageStyle}" x:Name="Page">
    <navigation:Page.Resources>

        <local:StudentViewModel x:Key="ViewModel"/>

    </navigation:Page.Resources>
so, we have to declare the namespace of the view model class as above and then declare it as a static resource in the resource tag of the page.

Conclusion


The article shows how you can bind your control with a property that is located in the data context of parent control not to the control in which the item exist.



Page copy protected against web site content infringement by Copyscape

About the Author

Shahvimall
Full Name: vimal shah
Member Level: Starter
Member Status: Member
Member Since: 10/11/2012 11:36:29 PM
Country: India
http://vimalshah26-howdowedoit.blogspot.in/

Vimal is a .Net Developer who has exposure to C#, VB, WPF, WCF, Silver Light, ADO.NET, SQL

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)