我有一个多页MVVM-Light应用程序,除了在弹出窗口中进行绑定之外,其他都运行良好。
我有一个弹出窗口,当单击MainWindow中的按钮时会显示该窗口。这可以正常工作,单击按钮时窗口可以正确显示,但是我想做的是在单击按钮时向弹出窗口添加一些按钮以执行一些命令,这是我遇到的问题,由于某些原因,XAML文件未与ViewModel绑定。
知道我想念什么吗?
弹出窗口出现以下警告:
System.Windows.Data错误:40:BindingExpression路径错误: 在“对象”“ ViewModelLocator”上找不到“ AboutViewModel”属性 (HashCode = 13742435)”。 BindingExpression:Path = AboutViewModel; DataItem ='ViewModelLocator'(HashCode = 13742435);目标元素是 'AboutView'(名称='');目标属性是“ DataContext”(类型 '对象')
这是我的代码。
<Window x:Class="MyApp.Views.AboutView"
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.galasoft.ch/ignore"
mc:Ignorable="d ignore"
Title="About MyApp" Height="340" Width="500"
ResizeMode="NoResize"
WindowStartupLocation="CenterOwner"
DataContext="{Binding AboutViewModel, Source={StaticResource Locator}}">
<Grid>
<Button x:Name="Ok" Command="{Binding ExitCommand}" Content="Ok"/>
</Grid>
</Window>
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using System;
using MyApp.ViewModel;
using MyApp.Views;
using System.Windows;
using System.Windows.Input;
namespace MyApp.ViewModel
{
public class AboutViewModel : ViewModelBase
{
public RelayCommand ExitCommand { get; private set; }
public AboutViewModel()
{
ExitCommand = new RelayCommand(() => ExitWindow());
}
private void ExitWindow()
{
Console.WriteLine("Exiting Window...");
}
}
}
我不确定这里到底是什么。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MyApp.ViewModel;
using MyApp.Views;
namespace MyApp.ViewModel
{
public class ViewModelLocator
{
private static MainViewModel _main;
private static AboutViewModel _about;
/// <summary>
/// Initializes a new instance of the ViewModelLocator class.
/// </summary>
public ViewModelLocator()
{
_main = new MainViewModel();
_about = new AboutViewModel();
}
/// <summary>
/// Gets the Main property which defines the main viewmodel.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance",
"CA1822:MarkMembersAsStatic",
Justification = "This non-static member is needed for data binding purposes.")]
public MainViewModel Main
{
get
{
return _main;
}
}
/// <summary>
/// Gets the Main property which defines the main viewmodel.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance",
"CA1822:MarkMembersAsStatic",
Justification = "This non-static member is needed for data binding purposes.")]
public AboutViewModel About
{
get {
return _about;
}
}
public static void Cleanup()
{
}
}
}
答案 0 :(得分:1)
DataContext源指向具有属性“关于”的“定位器”,但在绑定中它指向属性“ AboutViewModel”。在那里只需要稍作修正即可。