juanvan
juanvan

Reputation: 681

ViewModelLocator.AutoWireViewModel - No DataContext for MainWindow

MainWindow UI

<Window x:Class="PrismSanity.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:prism="http://prismlibrary.com/"
        prism:ViewModelLocator.AutoWireViewModel="True"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>

        <TextBlock Text="{Binding MyName}"></TextBlock>


    </Grid>
</Window>

MainWindowViewModel

public class MainWindowViewModel : BindableBase
    {

        private string _MyName = "John";

        public string MyName
        {
            get { return _MyName = "John"; }
            set { SetProperty(ref _MyName, value); }
        }


    }

I installed SNOOP to see what was happening, but the VM is not being Linked to the View. If I do the same thing with a second view, and use

<ContectContainer>
<views:ViewA/>
</ContentContainer>

in the Mainwindow Then I get the ViewA and ViewAViewModel to link fine. Thanks for looking.

Upvotes: 0

Views: 1073

Answers (1)

blogprogramisty.net
blogprogramisty.net

Reputation: 1762

Prism supports only UserControl class not Window class. AutoWireViewModel wokrs only with UserControl class.

I have the same problem I resolve this binding the context in code behind - partial using Unity. Something like that:

public partial class ShellView : Window
{
    public ShellView(ShellViewModel viewModel)
    {
        this.InitializeComponent();

        // Set the ViewModel as this View's data context.
        this.DataContext = viewModel;
    }

When app create the ShellView (it is your PrismSanity.MainWindow) unity inject the viewModel (ShellViewModel )

It is little technology debt.

Upvotes: 3

Related Questions