c# - 创建新类时如何传递类的实例?

标签 c#

这是我想做的:

public partial class PhrasesFrame : Frame
{
    public PhrasesFrameViewModel vm = new PhrasesFrameViewModel(this);

    public PhrasesFrame()
    {
        InitializeComponent();
    }

public class PhrasesFrameViewModel : ObservableProperty
{

    PhrasesFrame phrasesFrame;

    PhrasesFrameViewModel(PhrasesFrame phrasesFrame) {
        this.phrasesFrame = phrasesFrame;
    }

我想为新的 PhrasesFrameViewModel 提供对创建它的类的引用。

但是我收到消息:

Keyword "this" is not available in the current context

最佳答案

在构造函数中创建 View 模型,以便在正确的上下文中访问 this 关键字。

public partial class PhrasesFrame : Frame {
    public PhrasesFrameViewModel vm;

    public PhrasesFrame() {
        InitializeComponent();
        vm = new PhrasesFrameViewModel(this);
    }

    //...
}

这假定 View 模型有一个可公开访问的构造函数,该构造函数接受传递的参数。

public class PhrasesFrameViewModel : ObservableProperty {

    private readonly PhrasesFrame phrasesFrame;

    public PhrasesFrameViewModel(PhrasesFrame phrasesFrame) {
        this.phrasesFrame = phrasesFrame;
    }

    //...
}

关于c# - 创建新类时如何传递类的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47957992/

相关文章:

c# - 项目为 64 位时的奇怪(对我来说)Caliburn.Micro 行为

c# - 同步两个 RichTextBox 的滚动位置?

c# - 在二叉搜索树 C# 中查找节点值

c# - 如何调用顶级构造函数?

c# - 自定义迭代器的实现不会更改其参数之一

c# - 以不同的方式加入列表

c# - 从内存加载 C# 中的数据 LOCAL INFILE

c# - 为什么 ComputeHash 的执行速度比 certutil -hashfile 慢得多?

c# - 将一个 exe 的输出重定向到另一个 exe : C#

C# - Process.Start ClickOnce 应用程序?什么网址?