【问题标题】:Set DataContext in WPF XAML to a specific object将 WPF XAML 中的 DataContext 设置为特定对象
【发布时间】: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

标签: c# wpf xaml


【解决方案1】:

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

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

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

【讨论】:

  • 当我使用你的 XAML 解决方案时,我得到一个 System.Windows.Markup.XamlParseException :( 但是 DataContext = viewmodel 解决方案可以完成这项工作。
  • 稍等一下,我会尝试纠正我的答案。我更精通 Xamarin 方言。
  • 显然你不能简单地绑定DataContext,即使我们没有使用DataContext作为绑定源。我会更新我的答案。
猜你喜欢
  • 2014-07-06
  • 1970-01-01
  • 1970-01-01
  • 2013-02-19
  • 1970-01-01
  • 1970-01-01
  • 2016-12-06
  • 1970-01-01
相关资源
最近更新 更多