[英]MVVM Light & WPF - Binding Multiple instances of a Window to a ViewModel
我正在研究MVVM中的第一個項目,我選擇使用MVVM Light Toolkit。 我有一個GameViewModel
可以在我的游戲主屏幕上處理業務。 我需要了解如何在執行命令時將Adventurer
實例作為參數打開一個新窗口( AdventurerView
),將其綁定到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
}
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>
GameViewModel
中的命令將有希望使這一切發生(消息框只是確認命令正在激活):
private void ExecuteShowAdvCommand(Adventurer adv)
{
System.Windows.MessageBox.Show(adv.Name);
}
我真的不知道還包括什么。
好的,我整理了一個演示版本,可以讓您更輕松地下載鏈接
功能:
MainWindow
, ModalWindow
, NonModalWindow
) MainWindow
有一個TextBox
你可以輸入你想要的任何內容。 TextBlock
顯示MainWindow的TextBox
中的消息。 CheckBox
來更新MainWindow
中結果文本塊中的值(對於模態窗口,這將在模態窗口關閉時啟動。對於NonModal更改可以看作asap) 這就是功能,
概念:
SimpleIoC
和使用GetInstance(...)
要求他們出去。 OpenWindowMessage
Messenger類用法 重要說明: - 此示例中用於從模式窗口設置非DP DialogResult
的方法不是MVVM友好的因為它使用代碼隱藏來設置應該避免的Window.Closing
事件上的DialogResult
屬性(如果需要的話) “可測”)。 我喜歡的方法有點長,在這里有很好的記錄(問答的混合)。 因此,為什么我為了這個樣本而忽略了它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.