WPF & SimpleMVVM: Binding new viewmodel to view

297 views Asked by At

Please note that this question is specific to SimpleMVVM and the use of its ViewModelLocator.

I have a view setup like so:

<UserControl x:Class="CallTracker.WPF.Views.CallUserControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 

             DataContext="{Binding Source={StaticResource Locator}, Path=CallViewModel}">

    <StackPanel>
        <TextBlock Text="{Binding GreetingText}" />
    </StackPanel>
</UserControl>

And my locator defines the CallViewModel as:

// Create CallViewModel on demand
public CallViewModel CallViewModel
{
    get
    {
        return _CallViewModel;
    }
    set
    {
        if (_CallViewModel != value)
        {
            _CallViewModel = value;
        }
    }
}
private CallViewModel _CallViewModel;

During execution I am trying to create a new CallUserControl to use but, using Snoops, I can see that the datacontext of CallUserControl is not being bound to the viewmodel (the datacontext in Snoops says null).

Stepping thru the code I can see that the CallViewModel is getting created and assigned to the object within the locator but the UserControl's datacontext is not binding to this newly created object.

I am creating the new CallViewModel as such:

private void NewCall()
{
    MessageBox.Show("NewCallCommand executed.");

    // Only start a new call if one doesn't currently exist
    if((App.Current.Resources["Locator"] as ViewModelLocator).CallViewModel == null)
    {
        CurrentCallViewModel = new CallViewModel();
    }
}

....

    /// <summary>
    /// Current MainContentViewModel 
    /// </summary>
    public CallViewModel CurrentCallViewModel
    {
        get
        {
            //Visibility _visible = (new ViewModelLocator()).CallViewModel == null ? Visibility.Collapsed : Visibility.Visible;
            return (App.Current.Resources["Locator"] as ViewModelLocator).CallViewModel;
        }
        set
        {
            if (this._CurrentCallViewModel != value)
            {
                this._CurrentCallViewModel = value;
                (App.Current.Resources["Locator"] as ViewModelLocator).CallViewModel = value;
                NotifyPropertyChanged(m => m.CurrentCallViewModel);
            }
        }
    }
    private CallViewModel _CurrentCallViewModel = null;

Anyyou know why this new ViewModel would not bind to the new Model? Is there some mechanism similar to NotifyPropertyChanged that I have to call from the locator to get the objects to bind?

0

There are 0 answers