Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • WPF : How to use RelativeSource with WPF binding?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 748
    Comment on it

    The RelativeSource is a markup extension that is used in for binding purpose in following scenarios :
    1)  To bind a property of a given object to another property of the object itself
    2)  To bind a property of a object to another one of its relative parents
    3)  To bind a property of a object to a piece of XAML
    4)  Finally for using differential of a series of a bound data.

     

    All of the above situations are expressed as RelativeSource property. Using the property we can  specify a binding in a style/template. In WPF if not explicitly defined , bindings inherit the data context from the DataContext, provided it  has been set earlier in the application. However RelativeSource property provides us a way to  explicitly set the source of a Binding and override the inherited data context.

    Following are the different modes in which we work with RelativeSource property for data binding purpose in an application:

     

    1. Self
       This mode  allows you to bind one property of an  element to another property on the same element and is used frequently , it is used as below:

     

     {Binding Path=PathToProperty, RelativeSource={RelativeSource Self}}

     

    2. TemplatedParent
       This mode is used with templates and is only applicable if the binding is within a template. The property in this scenario refers to the element to which the template containing  the data-bound   element is applied.

     

    {Binding Path=PathToProperty, RelativeSource={RelativeSource TemplatedParent}}

     

    3. FindAncestor
       This mode refers to the ancestor in the parent chain of the data-bound element. Using the below syntax we can use this mode to bind to an ancestor of a specific type or its child classes.

     

     {Binding Path=PathToProperty, RelativeSource={RelativeSource AncestorType={x:Type typeOfAncestor}}}

     

    4. PreviousData
       This is relatively a lesser used mode for RelativeSource property  and allows the user  to bind to the previous data item  in the collection of data items displayed.

     

    In this blog we have learned the basics of RelativeSource  property. Do check out  the official documentation for more detailed information at:

    Reference : https://msdn.microsoft.com/en-us/library/system.windows.data.relativesourcemode.aspx

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: