Jas*_*n D 6 c# wpf mvvm mvvm-light
我正在研究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 x:Key="Locator" d:IsDataSource="True" />
<DataTemplate DataType="{x:Type vm:GameViewModel}">
<views:GameView />
</DataTemplate>
<DataTemplate DataType="{x:Type vm:TitleViewModel}">
<views:TitleView />
</DataTemplate>
<DataTemplate DataType="{x:Type vm:AdventurerViewModel}">
<views:AdventurerView />
</DataTemplate>
</Application.Resources>
</Application>
Run Code Online (Sandbox Code Playgroud)
GameViewModel希望这个命令能够完成这一切(消息框只是确认命令正在激活):
private void ExecuteShowAdvCommand(Adventurer adv)
{
System.Windows.MessageBox.Show(adv.Name);
}
Run Code Online (Sandbox Code Playgroud)
我真的不知道还包括什么.
Viv*_*Viv 23
好的,我整理了一个演示版本,可以让您更轻松地下载链接
功能:
MainWindow,ModalWindow,NonModalWindow)MainWindow有TextBox你可以输入任何你想要的东西.TextBox在TextBlock里面他们.CheckBox来更新结果的文本块中的值MainWindow(对于模态窗口,这将在模态窗口关闭时启动.对于NonModal更改可以看作asap)这就是功能,
概念:
SimpleIoC使用和注册多个VM GetInstance(...)来请求它们.OpenWindowMessage重要说明:
- 本示例中用于DialogResult从模态窗口设置非DP 的方法不是MVVM友好的因为它使用代码隐藏来设置应该避免DialogResult的Window.Closing事件的属性(如果需要"可测试").我喜欢的方法有点长,在这里有很好的记录(问答的混合).因此,为什么我为了这个样本而忽略了它.