我在应用 MVVM 模式时遇到了一些麻烦,首先我按照这个例子来学习如何应用和使用模式......
http://msdn.microsoft.com/en-us/magazine/dd419663.aspx
所以我的问题是在 View 与 ViewModel 之间建立“连接”......
在示例中,我们有一个带有 CollectionViewSource 的 View,其中 Source 是 AllCustomers 属性:
<UserControl
x:Class="DemoApp.View.AllCustomersView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase">
<UserControl.Resources>
<CollectionViewSource x:Key="CustomerGroups" Source="{Binding Path=AllCustomers}"/>
</UserControl.Resources>
<DockPanel>
<ListView AlternationCount="2" DataContext="{StaticResource CustomerGroups}" ItemsSource="{Binding}">
<ListView.View>
<GridView>
<GridViewColumn Header="Name" DisplayMemberBinding="{Binding Path=DisplayName}"/>
<GridViewColumn Header="E-mail" DisplayMemberBinding="{Binding Path=Email}"/>
</GridView>
</ListView.View>
</ListView>
</DockPanel>
</UserControl>
谁属于 ViewModel AllCustomersViewModel:
public class AllCustomersViewModel : WorkspaceViewModel
{
(...)
public ObservableCollection<CustomerViewModel> AllCustomers { get; private set; }
(...)
}
但他使用 ResourceDictionary 在 View 和 ViewModel 之间应用 DataTemplate:
<DataTemplate DataType="{x:Type vm:AllCustomersViewModel}">
<vw:AllCustomersView />
</DataTemplate>
但我的问题是因为我没有使用 ResourceDictionary,因此我认为我可以将 DataTemplate 放在我将拥有我的 View 的窗口的资源中(对我来说是放置 DataTemplate 的更多逻辑位置)。 .. 但由于某种原因,数据没有出现在 ListView 中,所以我问为什么?
最佳答案
我不会在 Xaml 中附加 View 模型。这会将 Xaml 硬编码为特定的 View 模型。
相反,我会覆盖应用程序启动:
private void OnStartup(object sender, StartupEventArgs e)
{
Views.MainView view = new Views.MainView();
view.DataContext = new ViewModels.MainViewModel();
view.Show();
}
见这篇文章:
http://www.codeproject.com/KB/WPF/MVVMQuickTutorial.aspx
如果您将来使用某种工具(如 MEF、CaSTLe.Windsor 或 Prism)动态绑定(bind) View 模型,这种方法也很有帮助。
关于wpf - 应用 MVVM 模式时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7223410/