简体   繁体   English

窗口绑定到UserControl ViewModel

[英]Window Binding to UserControl ViewModel

I need help with binding a window to a user control view model. 我需要将窗口绑定到用户控件视图模型的帮助。 Here's my user control, nice and simple. 这是我的用户控件,非常简单。

<UserControl x:Class="WindowBindTest.UserControlTest"
         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" 
         mc:Ignorable="d" 
         xmlns:ViewModel="clr-namespace:WindowBindTest.UserControlViewModel"
         d:DesignHeight="300" d:DesignWidth="300">
<UserControl.DataContext>
<ViewModel:UserControlViewModel></ViewModel:UserControlViewModel>
</UserControl.DataContext>
<Grid>            
</Grid>
</UserControl>

Here's my view model 这是我的视图模型

namespace WindowBindTest
{
    public class UserControlViewModel
    {
        public Window hostWindow { get; set; }|
        public UserControlViewModel()
        {
            // I want to set the host window
            // If something isn't defined then close the host window.
        }    

    }
}

I could use a button to close the window but what if I didn't want to use a button. 我可以使用按钮关闭窗口,但是如果我不想使用按钮怎么办。 Is there a way to do that? 有没有办法做到这一点? Could I pass in the parent window into the constructor? 我可以将父窗口传递给构造函数吗?

You can do this in MVVM but you will need to use a service. 您可以在MVVM中执行此操作,但需要使用服务。 In fact, this is where MVVM is weak (without using a framework such as Prism et al.). 实际上,这就是MVVM薄弱的地方(不使用Prism等人的框架)。 The following is a link to disore's DialogService class on CodeProject . 以下是在CodeProject上disore的DialogService类的链接。 it is awesome, but it will take time to get to grips with how it works. 很棒,但是要花些时间才能掌握它的工作原理。

The above library will enable you to close a View from a ViewModel. 上面的库使您可以从ViewModel关闭View。

I hope this helps. 我希望这有帮助。

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

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