我正在研究MVVM中的第一个项目,我选择使用MVVM Light Toolkit.我有一个GameViewModel在我的游戏主屏幕上处理业务.我需要找到如何在执行命令时将AdventurerView一个实例Adventurer作为参数打开一个新窗口(),绑定它AdventurerViewModel,并显示和返回数据.此窗口的实例将经常打开和关闭.我已经被困在这几天了,这让我发疯了.我想学习如何以MVVM友好的方式执行此操作,最好使用MVVM Light或纯XAML提供的工具.
我尝试过使用MVVM Light,ViewModelLocator但由于AdventurerView它是一个窗口,它将无法工作; 虽然程序仍在编译和运行,但它说"不能把窗口放在一个样式中".我可以改变一些东西让它起作用吗?或者是否有另一种方法在XAML中绑定它们?或完全是另一种方法?我真的很想能够继续前进.我也试过使用MVVM Light的信使无济于事(仍然没有解决View/ViewModel问题).
我只需要能够创建一个绑定的窗口AdventurerViewModel并显示/返回相应的数据.
AdventurerView.xaml目前处于默认状态,但我觉得如果我可以绑定可能有用的相应数据(DataContext).
AdventurerViewModel也很简单
class AdventurerViewModel : ViewModelBase
{
#region Members
private Adventurer _adv;
#endregion
#region Properties
public Adventurer Adv
{
get { return _adv; }
set { _adv = value; }
}
#endregion
#region Construction
public AdventurerViewModel(Adventurer adv)
{
this._adv = adv;
}
#endregion
}
Run Code Online (Sandbox Code Playgroud)
App.xaml底部有非工作的DataTemplate:
<Application StartupUri="MainWindow.xaml"
xmlns:views="clr-namespace:AoW.Views"
xmlns:vm="clr-namespace:AoW.ViewModels"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="AoW.App"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Application.Resources>
<vm:ViewModelLocator …Run Code Online (Sandbox Code Playgroud) 我有以下内容ControlTemplate:
<ContentControl Content="{Binding ContentViewModel}">
<ContentControl.Resources>
<DataTemplate DataType="{x:Type viewModel:FilledContentViewModel}">
<usercontrols:FilledMainWindow x:Name="MainContent" />
</DataTemplate>
<DataTemplate DataType="{x:Type viewModel:EmptyContentViewModel}">
<!-- todo: Something like a StartPage here -->
</DataTemplate>
</ContentControl.Resources>
</ContentControl>
Run Code Online (Sandbox Code Playgroud)
这非常有效,直到视图模型尝试将ContentViewModel属性从 1更改FilledContentViewModel为新的FilledContentViewModel,然后 的内容ContentControl不会刷新。如果从EmptyContentViewModel到FilledContentViewModel或相反的方式切换,它就会起作用。
当然,仅更新现有的所有内容FilledContentViewModel也是一种解决方案。但我认为它可能会很快变得混乱,而只需使用ViewModel正确的上下文创建一个新的并切换它会更优雅。
有谁知道有什么方法可以让内容刷新DataTemplate吗?