简体   繁体   English

如何绑定到用户控件的父窗口IsActive属性

[英]How to bind to user control's parent window IsActive property

I had my WPF control set so that it had only the following code: 我设置了WPF控件,使其仅具有以下代码:

  InitializeComponent();
  DataContext = model; 

However, I now run into a problem where I do not want certain actions to occur while the window is not active, so I created an IsActive flag on my ViewModel, but as my code is coming from a user control, and not a window, I cannot do this without code behind in my user control. 但是,我现在遇到一个问题,我不希望在窗口不处于活动状态时执行某些操作,因此我在ViewModel上创建了一个IsActive标志,但是由于我的代码来自用户控件而不是窗口,如果没有用户控件中的代码,我将无法做到这一点。 Is this the best I can do, or is there a true MVVM approach to this 这是我所能做到的最好吗,还是有一种真正的MVVM方法

Tried this, but ran into a runtime error saying that the IsActiveProperty cannot be data bound. 尝试过此操作,但遇到运行时错误,指出IsActiveProperty无法绑定数据。

 Loaded += (sender, args) =>
              {
                var parentWindow = Window.GetWindow(this);
                if (parentWindow == null)
                  return;
                var isActiveWindowBinding = new Binding {Source = model.IsActive};
                parentWindow.SetBinding(Window.IsActiveProperty, isActiveWindowBinding);
              };

So, I am not doing this: 因此,我没有这样做:

 Loaded += (sender, args) =>
              {
                var parentWindow = Window.GetWindow(this);
                if (parentWindow == null)
                  return;
                parentWindow.Activated += (o, eventArgs) => model.IsActive = true;
                parentWindow.Deactivated += (o, eventArgs) => model.IsActive = false;
              };

The biggest problem is that I cannot get the parent window until the control loads and databinding has already been completed? 最大的问题是,直到控件加载并且数据绑定已经完成,我才能获取父窗口? Would I have to create an attached behavior, which is quite a lot of pain for a simple binding. 我是否必须创建一个附加的行为,这对于简单的绑定是非常痛苦的。

Does not binding work? 不绑定吗?

<Window IsActive="{Binding Path=IsActive, Mode=OneWayToSource}"/>

Here is meant that DataContext of the window is set. 这意味着已设置窗口的DataContext。

Or if you want to use window's state in user control markup, try this binding: 或者,如果您想在用户控件标记中使用窗口的状态,请尝试以下绑定:

PropValue="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}, Path=IsActive}"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM