HarryKane
HarryKane

Reputation: 168

Set DataContext in WPF XAML to a specific object

I started a WPF window from a console application. But I have difficulties with the databinding.

TL;DR: Is it possible to refer to a specific (view)model object in the WPF XAML?

This is my Code:

Console.cs A console application starts the view with a static function in the void Main() function

static void StartGUI(ViewModelClass viewmodel)
{
    Thread thread = new Thread(() => { new Application().Run(new View.MainWnd(viewmodel)); });
    thread.SetApartmentState(ApartmentState.STA);
    thread.Start();
}

it gets the viewmodel object which has been initiated in the Main().

ViewModel.cs The viewmodel is the usual impelemtation of the INotifyPropertyChanged interface with a property to be bound to the view.

using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;

using ConsoleStartsGUI.Model;

namespace ConsoleStartsGUI.ViewModel
{
    public class ViewModelClass : INotifyPropertyChanged
    {
        ModelClass model = new ModelClass();

        public string VMProperty
        {
            get { return model.TestProperty; }
            set
            {
                model.TestProperty = value;
                OnPropertyChanged();
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged([CallerMemberName] String propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

View.xaml In the view I get my problems: The view should know the same viewmodel as the console application.

Currently I use

<Window.DataContext>
    <ViewModel:ViewModelClass/>
</Window.DataContext>

to bind the viewmodelclass to the view (this is the result I clicked in the VS designer) as it usually works when I use a WPF project from begin. But this instantiates a new object, which is not the object of the console application.

View.xaml.cs

using System.Windows;
using ConsoleStartsGUI.ViewModel;

namespace ConsoleStartsGUI.View
{
    public partial class MainWnd : Window
    {
        public MainWnd(ViewModelClass viewmodel)
        {
            InitializeComponent();
        }
    }
}

Is there a way, to refer to a specific (view)model object in the XAML?

Best regards, Martin

Upvotes: 0

Views: 2145

Answers (1)

Paul Kertscher
Paul Kertscher

Reputation: 9713

Yes, this is possible: Just assign the DataContext from your constructor

class MainWindow : Window
{
    public MainWindow(ViewModelClass viewmodel)
    {
        InitializeComponent();
        this.DataContext = viewmodel; // should work before as well as after InitalizeComponent();
    }
}

Binding it from the XAML obviously does not work, for some reason.

Upvotes: 2

Related Questions