InfernumDeus
InfernumDeus

Reputation: 1202

Bind Window object to viewmodel property from XAML

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.

Upvotes: 0

Views: 1019

Answers (1)

dontbyteme
dontbyteme

Reputation: 1261

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();

Upvotes: 3

Related Questions