从视图模型获取窗口 [英] Getting Window from view model

查看:79
本文介绍了从视图模型获取窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个自定义的messageBox窗口来替换典型的MessageBox.

I have created a custom messageBox Window to replace the typical MessageBox.

我的自定义messageBox(子窗口)需要将父窗口作为参数传递.父窗口是子窗口将在指定位置(左上角,顶部居中等)内作为参数的位置.

My custom messageBox (child Window) needs parent window to be passed as an argument. The parent window is where child window will be located within in the location specified (Top Left, Top Center, etc.) also as an argument.

因此,当从视图模型调用我的自定义messageBox时,我需要使Window通过它.如何获取与视图模型关联的窗口?

So when calling my custom messageBox from view model, I need to get the Window to pass it through. How can I get the Window associated to the view model?

也许在此处这样的界面上使用?我正在尝试实现它,但是this.DataContext.View不存在.

Maybe using an Interface like commented here? I am trying to implement it but this.DataContext.View does not exist.

我正在使用Visual Studio 2008.

I am using Visual Studio 2008.

ATTEMPT#1 :mm8解决方案

<Window x:Class="MyNamespace.Main"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:viewmodel="clr-namespace:MyNamespace.ViewModels">
    <Window.Resources>
        <viewmodel:MainViewModel x:Key="wMainViewModel" />
    </Window.Resources>

    <Grid DataContext="{StaticResource wMainViewModel}">
    </Grid>
</Window>

考虑到我是从xaml初始化DataContext的,而不是从构造函数的代码隐藏的,所以如何将视图传递给视图模型?

Taken into account that I initialize DataContext from xaml and not in code-behind from constructor, how can I pass the view to the view model¿?

推荐答案

如何获取与视图模型关联的窗口?

How can I get the Window associated to the view model?

您可以使用窗口实现的接口注入视图模型:

You could inject the view model with an interface that the window implements:

public interface IView
{
    double Top { get; }
    double Left { get; }
    double Height { get; }
    double Width { get; }
}

public partial class MainWindow : Window, IView
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ViewModel(this);
    }
}

public class ViewModel
{
    private readonly IView _view;

    public ViewModel(IView view)
    {
        _view = view;
    }

    //...
}

然后,视图模型只知道一个接口(可能应该将其称为IView之外的其他名称).

Then the view model knows only about an interface (which maybe should be called something else than IView).

如果您想要一个丑陋且非MVVM友好的快捷方式,则可以使用Application类:

If you want an ugly and non-MVVM friendly shortcut, you could use the Application class:

var win = Application.Current.MainWindow;

创建所有内容的工厂类:

A factory class to create everything:

public MainWindow WindowFactory()
{
    MainWindow mainWindow = new MainWindow();
    ViewModel viewModel = new ViewModel();
    mainWindow.DataContext = viewModel;

    return mainWindow;
}

这篇关于从视图模型获取窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆