简体   繁体   中英

Binding a button action to a Child ViewModel with Caliburn.Micro

This should be easy, but its not working for me. I have a view called MainWindowView that contains a view called ChildView. The MainWindowView has a corresponding ViewModel called MainWindowViewModel and the ChildView has a ViewModel called ChildViewModel:

MainWindowView:

<Grid>
    <views:ChildView x:Name="ChildView"/>
</Grid>

MainWindowViewModel:

public MainWindowViewModel()
{
    ChildView = new ChildViewModel();
}

ChildView:

<Grid>
    <Button Content="Edit" x:Name="Edit"/> 
</Grid>

ChildViewModel:

public class ChildViewModel
{
    public void Edit()
    {

    }

    public ChildViewModel()
    {

    }

EDIT:

AppBootstrapper:

public class AppBootstrapper : BootstrapperBase
{
    private SimpleContainer container;

    public AppBootstrapper()
    {
        Initialize();
    }

    protected override void Configure()
    {
        container = new SimpleContainer();

        container.Instance(container);

        container
            .Singleton<IWindowManager, WindowManager>()
            .Singleton<IEventAggregator, EventAggregator>();

        container.PerRequest<MainWindowViewModel>();
    }

    protected override void OnStartup(object sender, StartupEventArgs e)
    {
        DisplayRootViewFor<MainWindowViewModel>();
    }

    protected override object GetInstance(Type service, string key)
    {
        return container.GetInstance(service, key);
    }

    protected override IEnumerable<object> GetAllInstances(Type service)
    {
        return container.GetAllInstances(service);
    }

    protected override void BuildUp(object instance)
    {
        container.BuildUp(instance);
    }

    protected override void OnUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
    {
        e.Handled = true;
        MessageBox.Show(e.Exception.Message, "An error as occurred", MessageBoxButton.OK);
    }
}

and I might add that the views are in a root level Views folder and the view models are in a root level ViewModels folder. Why won't the Edit command fire?

well I am gonna go our on a limb and say that from my experience with CM and say that from what you have a shown there is probably a binding error. What is supposed to happen? Keep in mind CM is not view first out of the box with WPF. Can you show us your bootstrapper?

I was able to fix this by changing the MainWindowView to

<Grid>
    <ContentControl x:Name="ChildView" />
</Grid>

Somehow Caliburn.Micro was not able to bind the ChildView to its ViewModel properly. I was confused because the ChildViewModel constructor was being called. I guess that Caliburn.Micro knows how to bind the ContentControl, but not my custom view.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM