来自新 window 的 WPF 绑定

WPF binding from new window

我需要在更改独立的用户控件后修复绑定 window。基本上现在我有两个 windows 使用 ShowDialog(),我将新的 window 连接到新的数据上下文

<Window.DataContext>
    <ViewModels:DatabaseDesignViewModel/>
</Window.DataContext>

但是现在我无法将按钮绑定到主视图的命令 window。

这就是我尝试解决它但运气不好的方法:

 <MenuItem Header="Go to design mode"
                  Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Views:RootView}}, Path=DataContext.OKCommand}"/>

首先 - 我同意 Dennis 的观点,你应该多考虑一下你的架构,但是你的请求当然有一个答案:

  1. 像这样创建附加的 属性:

    public class AttachedProperties
    {
        public static Window GetParentWindow( DependencyObject obj )
        {
            return (Window)obj.GetValue( ParentWindowProperty );
        }
        public static void SetParentWindow( DependencyObject obj, Window value )
        {
            obj.SetValue( ParentWindowProperty, value );
        }
        public static readonly DependencyProperty ParentWindowProperty =
            DependencyProperty.RegisterAttached( "ParentWindow", typeof( Window ), typeof( AttachedProperties ), new PropertyMetadata( null ) );
    }
    
  2. 将以下代码添加到您的 child windows xaml.cs:

    protected override void OnActivated( EventArgs e )
        {
            base.OnActivated( e );
            this.SetValue( AttachedProperties.ParentWindowProperty, Owner );
        }
    
  3. 在您的 child windows xaml 中,您可以使用以下绑定语法:

    <Window x:Class="WpfApplication3.ChildWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:local="clr-namespace:YourApplicationNamespace"
            x:Name="Self">
        <TextBlock Text="{Binding ElementName=Self, Path=(local:AttachedProperties.ParentWindow).DataContext.SomeProperty}" />
    </Window>