繁体   English   中英

窗口绑定到UserControl ViewModel

[英]Window Binding to UserControl ViewModel

我需要将窗口绑定到用户控件视图模型的帮助。 这是我的用户控件,非常简单。

<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>

这是我的视图模型

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.
        }    

    }
}

我可以使用按钮关闭窗口,但是如果我不想使用按钮怎么办。 有没有办法做到这一点? 我可以将父窗口传递给构造函数吗?

您可以在MVVM中执行此操作,但需要使用服务。 实际上,这就是MVVM薄弱的地方(不使用Prism等人的框架)。 以下是在CodeProject上disore的DialogService类的链接。 很棒,但是要花些时间才能掌握它的工作原理。

上面的库使您可以从ViewModel关闭View。

我希望这有帮助。

暂无
暂无

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

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