0

I have viewmodel like this:

public class ViewModel
{
    public IView View { get; set; }
}

And Window that implements IView.

I need to bind this exact Window to view property without changing ViewModel class.

Is this possible to do with only XAML of that Window?

I can do it this way: https://stackoverflow.com/a/47266732/3206223

But would have to change ViewModel which is undesirable in this case.

InfernumDeus
  • 1,185
  • 1
  • 11
  • 33

1 Answers1

2

You need to instantiate the ViewModel in XAML and set it as DataContext:

<Window x:Class="MyApp.AppWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:MyApp.ViewModels">
      <Window.DataContext>
           <local:ViewModel/>
      </Window.DataContext>
</Window>

Edit:

Change

window.DataContext = new ViewModel(properties);
window.ShowDialog();

to

var vm = new ViewModel(properties);
vm.View = window;
window.ShowDialog();
dontbyteme
  • 1,221
  • 1
  • 11
  • 23
  • I already bound ViewModel to DataContext (in other way but still). Now I need to bind this Window itself to ViewModel.View. – InfernumDeus Aug 21 '18 at 11:58
  • @InfernumDeus you just need to add the property View to your path like where Text ist the public property in IView you want to bind to for example – dontbyteme Aug 21 '18 at 12:02
  • The problem is I already know how to bind _data_ from IView. I need to bind this `` object to be able to access IView inside of VIewModel. – InfernumDeus Aug 21 '18 at 12:05
  • To make it clear I need Window object inside my `public IView View` property. – InfernumDeus Aug 21 '18 at 12:07
  • Okay, got it now. Where do you instantiate your ViewModel? Is there any possibility to pass your Window instance? – dontbyteme Aug 21 '18 at 12:10
  • Yes. As I stated in my question I can do that. But in this case I will have to change ViewModel's code which should be avoided if possible. – InfernumDeus Aug 21 '18 at 12:11
  • 1
    You don't need to change the ViewModels code itself, just the code where you set the DataContext of the Window... So again: Where do you instantiate the ViewModel object / where you set the DataContext? – dontbyteme Aug 21 '18 at 12:16
  • Oh... Now I get it. Thank you! – InfernumDeus Aug 21 '18 at 12:18