[英]Set DataContext in WPF XAML to a specific object
I started a WPF window from a console application. 我从控制台应用程序启动了WPF窗口。 But I have difficulties with the databinding.
但是我在数据绑定方面有困难。
TL;DR: Is it possible to refer to a specific (view)model object in the WPF XAML? TL; DR:是否可以在WPF XAML中引用特定的(视图)模型对象?
This is my Code: 这是我的代码:
Console.cs A console application starts the view with a static function in the void Main()
function 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();
}
it gets the viewmodel object which has been initiated in the Main()
. 它获取已经在
Main()
启动的viewmodel对象。
ViewModel.cs The viewmodel is the usual impelemtation of the INotifyPropertyChanged interface with a property to be bound to the view. 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 In the view I get my problems: The view should know the same viewmodel as the console application. View.xaml在视图中,我遇到了问题:该视图应与控制台应用程序具有相同的视图模型。
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. 将viewmodelclass绑定到视图(这是我在VS设计器中单击的结果),因为当我从一开始就使用WPF项目时,它通常可以工作。 But this instantiates a new object, which is not the object of the console application.
但这会实例化一个新对象,该对象不是控制台应用程序的对象。
View.xaml.cs 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? 有没有办法在XAML中引用特定的(视图)模型对象?
Best regards, Martin 最好的问候,马丁
Yes, this is possible: Just assign the DataContext
from your constructor 是的,这是可能的:只需从构造函数分配
DataContext
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. 由于某种原因,从XAML绑定它显然不起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.