将视图绑定到ViewModel,没有“空”构造函数

时间:2013-05-11 18:31:35

标签: c# wpf mvvm caliburn.micro

继续上一个问题“Updating/using a variable from another ViewModel”,我决定开始使用Caliburn Micro作为框架。

我根据本指南http://www.mindscapehq.com/blog/index.php/2012/02/01/caliburn-micro-part-4-the-event-aggregator/设置了Event Aggerator。

根据本指南,不应该有一个带有0个参数的“空”构造函数。

好吧。

现在问题是我不知道如何将ViewModel绑定到View。 在切换到这个框架之前,我使用了App.xaml和静态资源作为datacontext,但是由于没有空的构造函数,我不能再这样做了。

我该如何解决这个问题?我一直试图解决这个问题一个小时,但我一无所获。

一些代码:

[Export(typeof(ViewModelBase))]
public class ViewModelBase : INotifyPropertyChanged, IHandle<updateEvent>
{
    private Class _studclass;
    public AddStudentViewModel NewModel { get; private set; }

    public Class StudentClass
    {
        get { return _studclass; }
        set
        {
            _studclass = value;
            NotifyPropertyChanged("StudentClass");
        }
    }

    [ImportingConstructor]
    public ViewModelBase(AddStudentViewModel newModel, IEventAggregator events)
    {
        StudentClass = new Class();
        NewModel = newModel;
        Student asaf = new Student();
        asaf.Name = "Asaf";
        StudentClass.StudentList.Add(asaf);
        events.Subscribe(this);
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void NotifyPropertyChanged(string PropertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
        }
    }

    public void Handle(updateEvent msg)
    {
        StudentClass.StudentList.Add(msg.Student);
    }
}

这是“主要”视图模型。但是,我不能将它绑定到一个视图,所以数据没有显示...我甚至试图设置一个假数据......这可能没有你想象的那么好。

1 个答案:

答案 0 :(得分:1)

Caliburn.Micro使用惯例。因此,如果 ViewModels 文件夹中有ShellViewModel,它将在 Views 文件夹中查找ShellView

我建议您查看示例和documentation。一个很好的起点是安装 Caliburn.Micro.Start NuGet包(它引入Caliburn.Micro),然后编辑 App.xaml 文件,如文档中所述。

本质上,引导程序是一个应用程序资源,它会导致它被实例化,然后通过配置的IoC容器解析shell视图模型,找到相应的shell视图,执行绑定并使用Caliburn.Micro窗口管理器显示它

您也不需要在视图模型基类上实现INotifyPropertyChanged。 Caliburn.Micro包含PropertyChangedBase类型,Screen类型和Conductor类型。

相关问题