问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/35125315/viewmodellocator-autowireviewmodel-no-datacontext-for-mainwindow