0

我正在开发一个 MVVMLight / WPF 项目,需要添加一大块功能,其中包括多个视图和视图模型。我知道在不久的将来会在其他项目中使用同样的功能,所以我想把这个功能变成自己的项目,我可以根据需要添加到其他解决方案中,而无需或很少修改。

我首先添加了第二个 MVVMLight 项目(Beta),删除了标准的 MainWindow.xaml 和 MainViewModel.cs 文件,并创建了一个简单的 UserControl 和关联的视图模型。

<UserControl x:Class="Beta.View.TestView"
        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:ignore="http://www.ignore.com"
        mc:Ignorable="d ignore"
        DataContext="{Binding Test_VM, Source={StaticResource Locator} }">

    <Grid>
        <TextBlock Text="{Binding WelcomeMessage}" />
    </Grid>
</UserControl>



public class TestViewModel : ViewModelBase
{
    #region Properties

    public string WelcomeMessage
    {
        get
        {
            return "Hello World!";
        }
    }

    #endregion Properties

    #region Constructors

    /// <summary>
    /// Initializes a new instance of the TestViewModel class.
    /// </summary>
    public TestViewModel()
    {

    }

    #endregion Constructors
}

我可以添加 Beta 作为对原始项目 (Alpha) 的引用,并通过将视图插入堆栈面板来显示视图,如下所示:

<StackPanel Name="MasterStackPanel"
            DockPanel.Dock="Top">
    <beta:TestView />
</StackPanel>

执行此操作时,一切似乎都正常工作。我遇到的问题是当我尝试将属性从 TestViewModel 绑定到 TestView 时。

在 TestView 中,如果我这样做:

<TextBlock Text="Hello World" />

TestView 在运行时正确显示。但是当我将 TextBlock 绑定到这样的属性时:

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

该消息未显示,Beta 的定位器似乎被忽略(未绑定数据上下文),并且我从 Snoop 收到以下错误:

System.Windows.Data Error: 40 : BindingExpression path error: 'WelcomeMessage' property not found on 'object' ''MainViewModel' (HashCode=51013215)'. BindingExpression:Path=WelcomeMessage; DataItem='MainViewModel' (HashCode=51013215); target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String')
System.Windows.Data Error: 40 : BindingExpression path error: 'Test_VM' property not found on 'object' ''ViewModelLocator' (HashCode=22749765)'. BindingExpression:Path=Test_VM; DataItem='ViewModelLocator' (HashCode=22749765); target element is 'TestView' (Name=''); target property is 'DataContext' (type 'Object')

我相信这意味着 Test_VM 和 WelcomeMessage 的绑定正试图通过 Alpha Locator 而不是 Beta Locator 找到。我使用的是在每个项目中启动 MVVMLight 项目时默认创建的 ViewModelLocator。

是否有可能拥有第二个“定位器”,如果可以,我需要做什么才能使其工作?

4

1 回答 1

1

我认为您应该在系统的应用程序根目录中只有一个定位器,并在库项目中使用“MvvmLightLibs”库并在 alpha 项目中引用它并在定位器中添加一个 TestViewModel-Property。

于 2018-11-16T18:52:03.187 回答