Add this BindingProxy class to your project:
using System.Windows; namespace YourNameSpace { /// <summary> /// Add Proxy <ut:BindingProxy x:Key="Proxy" Data="{Binding}" /> to Resources /// Bind like <Element Property="{Binding Data.MyValue, Source={StaticResource Proxy}}" /> /// </summary> 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)); } }
- Add BindingProxy to UserControl resources.
- Set the Data property for BindingProxy to everything you need, for example. search parent window.
Data="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}},Path=DataContext}" If you need something more complex, you can use your own converter.
You now have access to this parent DataContext: {Binding Data.MyCommand, Source={StaticResource BindingProxy}}
<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:common="clr-namespace:YourNameSpace;assembly=YourAssembly" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300"> <UserControl.Resources> <common:BindingProxy x:Key="BindingProxy" Data="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}},Path=DataContext}" /> </UserControl.Resources> <Border> <Button Command="{Binding Data.MyCommand, Source={StaticResource BindingProxy}}">Execute My Command</Button> </Border> </UserControl>
jv_ Aug 27 '16 at 4:01 2016-08-27 04:01
source share