WPF绑定从新窗口

用户名

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

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

但是现在我很难将按钮绑定到来自主窗口的根视图的命令。

这就是我试图解决运气不佳的方法:

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

首先-我同意丹尼斯(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. 将以下代码添加到子窗口xaml.cs:

    protected override void OnActivated( EventArgs e )
        {
            base.OnActivated( e );
            this.SetValue( AttachedProperties.ParentWindowProperty, Owner );
        }
  3. 在子窗口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>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章