1

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

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

    }
}

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

4

1 回答 1

2

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

上面的库将使您能够从 ViewModel 关闭视图。

我希望这有帮助。

于 2013-09-12T15:34:05.793 回答