首页 > 解决方案 > 将 WPF XAML 中的 DataContext 设置为特定对象

问题描述

我从控制台应用程序启动了一个 WPF 窗口。但是我在数据绑定方面遇到了困难。

TL;DR:是否可以在 WPF XAML 中引用特定的(视图)模型对象?

这是我的代码:

Console.cs 一个控制台应用程序使用函数中的静态函数启动void Main()视图

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

它获取已在Main().

ViewModel.cs viewmodel 是 INotifyPropertyChanged 接口的常见实现,带有要绑定到视图的属性。

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 在视图中我遇到了问题:视图应该知道与控制台应用程序相同的视图模型。

目前我使用

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

将 viewmodelclass 绑定到视图(这是我在 VS 设计器中单击的结果),因为它通常在我从一开始就使用 WPF 项目时起作用。但这会实例化一个新对象,它不是控制台应用程序的对象。

查看.xaml.cs

using System.Windows;
using ConsoleStartsGUI.ViewModel;

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

有没有办法在 XAML 中引用特定的(视图)模型对象?

最好的问候,马丁

标签: c#wpfxaml

解决方案


是的,这是可能的:只需DataContext从您的构造函数中分配

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

由于某种原因,从 XAML 绑定它显然不起作用。


推荐阅读