0

私は MVVMLight / WPF プロジェクトに取り組んでおり、複数のビューとビューモデルを含む機能のチャンクを追加する必要があります。これと同じ機能が近い将来他のプロジェクトで使用されることを知っているので、この機能を独自のプロジェクトにして、必要に応じてほとんどまたはまったく変更せずに他のソリューションに追加できるようにしたいと考えています。

まず、2 つ目の MVVMLight プロジェクト (ベータ版) を追加し、標準の 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
}

元のプロジェクト (アルファ) への参照としてベータを追加し、ビューをスタック パネルに次のように挿入してビューを表示することができます。

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

これを行うと、すべてが適切に機能するように見えます。私が抱えている問題は、プロパティを TestViewModel から TestView にバインドしようとしたときです。

TestView で、これを行うと:

<TextBlock Text="Hello World" />

TestView は実行時に正しく表示されます。しかし、次のように TextBlock をプロパティにバインドすると:

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

メッセージは表示されず、ベータ版のロケーターは無視されているように見え (データコンテキストがバインドされていません)、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 のバインディングが Beta Locator ではなく Alpha Locator を介して検出されようとしていることを意味していると思います。各プロジェクトで MVVMLight プロジェクトを開始するときにデフォルトで作成される ViewModelLocator を使用しています。

2 番目の「ロケータ」を使用することは可能ですか? もしそうなら、それを機能させるために何をする必要がありますか?

4

1 に答える 1