Caliburn.Micro when setting VM to inherit Screen,

2019-07-18 08:47发布

问题:

If I have a ViewModel like so:

 public class ViewModel : IPropertyChangeBase, IViewModel
 {
 }

The "Title" property I set in the xaml of the view it's bound to properly shows.

If I have the ViewModel inherit from Screen instead what shows up in the title is the complete type name of the ViewModel, like "MarksProject.ViewModels.ViewModel." This shows up on the window's title.

 //View Title property being overriden.
 public class ViewModel : Screen, IViewModel
 {
 }

回答1:

Screen defines a property DisplayName that Caliburn.Micro uses to automatically populate headers. Just set that in the constructor like this:

public ViewModel() {
    this.DisplayName = "MyTitle";
}

And you'll have your title back - and saved a Property in the process ;)



回答2:

It is generally a bad idea to call virtual members (DisplayName) from a constructor as in @T045T's answer. This is a safer way:

public class ViewModel : Screen
{
    public override string DisplayName
    {
        get { return "View Title"; }
        set { }
    }
}

Note that set { } is needed to avoid Mode=TwoWay binding errors.