Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • WPF : Binding when DataContext not inherited

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 2.09k
    Comment on it

    Introduction :

    The DataContext property in WPF is extremely useful because it is inherited by all children. However there are situations where  the DataContext is not accessible as the elements are not part of the visual/logical tree. In such situations it can be very difficult to bind a property to those element. Freezable class comes to rescue in such situations .The interesting feature  that helps is that is that Freezable objects can inherit the DataContext even when they’re not in the visual/logical tree. We use this feature to make binding work

    Let us now see the the above concept practically. Context Menu is used as an example because it cannot directly access a DataContext outside itself. We will we create a proxy that allows for getting/setting of properties. This BindingProxy class inherits from Freezable and will be used for retrieval of DataContext.

    
    	class BindingProxy :Freezable {
    		protected override Freezable CreateInstanceCore() {
    			return new BindingProxy();
    		}
    		
    		public object Data {
    			get { return (object)GetValue(DataProperty); }
    			set { SetValue(DataProperty, value); }
    		}
    		
    		public static readonly DependencyProperty DataProperty = DependencyProperty.Register("Data", typeof(object), typeof(BindingProxy), new UIPropertyMetadata(null));
    	}


    We now  declare an instance of this class in the resources section. Further we  bind the Data property to the current DataContext:

     <local:BindingProxy  x:Key="DataContextProxy"  Data="{Binding}" />

     

    The last step  to  complete the implementation is to specify this BindingProxy object:

            <!--Context menu -->
            <ContextMenu x:Key="cntxtMenu" >
                <MenuItem Header="Create new" x:Name="MenuItemCreate" CommandParameter="{Binding}" Command="{Binding Data.ContextMenuCreateCommand, Source={StaticResource             DataContextProxy}}"/>         
            </ContextMenu>


    The binding now will now work correctly. Hope the above blog helped in understanding the solution of a common problem we encounter during data binding in WPF.

 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: