c# - 将 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 中引用特定的(视图)模型对象?
最好的问候,马丁
解决方案
是的,这是可能的:只需DataContext
从您的构造函数中分配
class MainWindow : Window
{
public MainWindow(ViewModelClass viewmodel)
{
InitializeComponent();
this.DataContext = viewmodel; // should work before as well as after InitalizeComponent();
}
}
由于某种原因,从 XAML 绑定它显然不起作用。
推荐阅读
- python-2.7 - 为什么 2.0 不能满足要求?
- flutter - 如何更改颤动应用程序键盘颜色?
- xcode11 - Swift Package Manager 与哪些 iOS 版本兼容?
- jquery - 如何为特定组件加载 slick-carousel 文件
- javascript - 如何在javascript中控制图像
- mergesort - 在 python 中实现合并排序时得到了错误的答案
- python - AttributeError:模块“张量板”没有属性“懒惰”
- php - 在多个 PHP 脚本中引用连接文件
- java.util.concurrent - 为什么在In AbstractQueuedSynchronizer中tryAcquire失败后会调用acquireQueued?
- java - 从谷歌助手等语音命令启动安卓应用