試圖讓我的頭繞過MVVM,並獲取一個簡單的窗口,通過數據模板將其viewmodel呈現爲視圖。設置Window.Content到ViewModel - 簡單的數據模板不工作
在App.xaml中:
<Application.Resources>
<DataTemplate DataType="{x:Type vm:TestViewModel}">
<vw:TestView />
</DataTemplate>
</Application.Resources>
視圖定義:
<UserControl x:Class="MyNamespace.TestView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<TextBlock>TESTING</TextBlock>
</Grid>
</UserControl>
在MainWindowViewModel:
private void onOpenTestView(object sender)
{
Window w = new Window();
w.Content = new TestViewModel();
w.Show();
}
運行在一個窗口中的應用程序搜索結果與 「MyNamespace.TestViewModel」字符串,而不是「測試」,這將推斷我的數據模板沒有被發現。
我對這一切都很陌生,所以我錯過了一些明顯的東西?我不認爲這是一個字符串匹配問題,因爲如果我故意拼錯XAML中的視圖或模型,那麼它不會編譯。
我的新窗口應該能夠訪問我的應用程序資源(以及我的數據模板)嗎?
乾杯, 傑里米
編輯:固定(不能回答8小時)
由於MS臭蟲,除非至少一個樣式設置沒有被讀取的資源。
對我來說看起來不像MVVM。 ViewModel不會創建視圖,也不會操作視圖。 – Will 2011-05-24 12:19:24
它不創建視圖,它創建視圖模型,WPF通過數據模板連接視圖。無可否認,它正在創建一個窗口,但我打算將其轉移到某個窗口管理器類。這還爲時尚早。 :) – GazTheDestroyer 2011-05-25 08:02:08