【问题标题】:WPF binding from new window从新窗口绑定 WPF
【发布时间】:2016-03-23 12:44:10
【问题描述】:

更改独立窗口的用户控件后,我需要修复绑定。基本上现在我有两个使用 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}"/>

【问题讨论】:

  • MenuItem 是 ContextMenu 的一部分吗?
  • FindAncestor 将不起作用,因为由于您移至独立窗口,RootView(据我了解,父窗口或它的一部分)不是“祖先”。每个窗口都有自己的逻辑和可视化树。
  • @Dennis 是否有办法访问这些命令,如果它们位于不同的逻辑和可视树中
  • @user5606505:很难说,因为我不知道,你如何创建你的视图模型和窗口。首先,当您需要来自父视图模型的命令时,这可能是一些架构问题。其次,如果您真的需要它,我会将MainViewModel Parent { get; } 之类的东西带入子视图模型。这将使绑定变得微不足道。

标签: c# wpf xaml data-binding binding


【解决方案1】:

首先 - 我同意丹尼斯的观点,你应该过度考虑你的架构,但你的要求当然有答案:

  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>

【讨论】:

    猜你喜欢
    • 2013-03-19
    • 1970-01-01
    • 2011-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多