How to access parent's DataContext from a UserControl

后端 未结 4 2076
旧时难觅i
旧时难觅i 2020-12-10 14:25

I need to access the container\'s DataContext from a UserControl (a grid containing textboxes and a listbox: I need to insert items in this list box) that I created in WPF:

4条回答
  •  一整个雨季
    2020-12-10 14:30

    Add this BindingProxy class to your project:

    using System.Windows;
    
    namespace YourNameSpace
    {
        /// 
        /// Add Proxy  to Resources
        /// Bind like    
        /// 
        public 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));
        }
    }
    
    1. Add the BindingProxy to your UserControl's resources.
    2. Set the 'Data' property of the BindingProxy to whatever you need, e.g. search for a parent Window. Data="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}},Path=DataContext}" If you needed something more complex you could use a custom converter.

    Now you have access to that parent's DataContext: {Binding Data.MyCommand, Source={StaticResource BindingProxy}}

    
        
            
        
        
            
            
        
    
    

提交回复
热议问题