Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

c# - Getting Window from view model

I have created a custom messageBox Window to replace the typical 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.

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?

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

I am using Visual Studio 2008.

ATTEMPT #1: mm8 solution

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

    //...
}

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...