【发布时间】:2019-01-30 12:36:20
【问题描述】:
我从控制台应用程序启动了一个 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 对象。
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 项目时起作用。但这会实例化一个新对象,它不是控制台应用程序的对象。
View.xaml.cs
using System.Windows;
using ConsoleStartsGUI.ViewModel;
namespace ConsoleStartsGUI.View
{
public partial class MainWnd : Window
{
public MainWnd(ViewModelClass viewmodel)
{
InitializeComponent();
}
}
}
有没有办法在 XAML 中引用特定(视图)模型对象?
最好的问候, 马丁
【问题讨论】:
-
在 InitializeComponent() 之后的构造函数中;写:DataContext = viewmodel;并从 XAML 中删除 Window.DataContext