【发布时间】:2010-04-14 22:13:17
【问题描述】:
众所周知,M-V-VM 的意义在于分散关注点。在 MVVM、MVC 或 MVP 等模式中,主要目的是将视图与数据分离,从而构建更灵活的组件。我将首先演示在许多 WPF 应用程序中发现的一个非常常见的场景,然后我将说明我的观点:
假设我们有一个 StockQuote 应用程序,它可以流式传输一堆报价并将它们显示在屏幕上。通常情况下,你会有这样的:
StockQuote.cs:(模型)
public class StockQuote
{
public string Symbol { get; set; }
public double Price { get; set; }
}
StockQuoteViewModel.cs : (ViewModel)
public class StockQuoteViewModel
{
private ObservableCollection<StockQuote> _quotes = new ObservableCollection<StockQuote>();
public ObservableCollection<StockQuote> Quotes
{
get
{
return _quotes;
}
}
}
StockQuoteView.xaml(视图)
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="Window1" Height="300" Width="300">
<Window.DataContext>
<local:StockQuoteViewModel/>
</Window.DataContext>
<Window.Resources>
<DataTemplate x:Key="listBoxDateTemplate">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Symbol}"/>
<TextBlock Text="{Binding Price}"/>
</StackPanel>
</DataTemplate>
</Window.Resources>
<Grid>
<ListBox ItemTemplate="{StaticResource listBoxDateTemplate}" ItemsSource="{Binding Quotes}"/>
</Grid>
</Window>
然后您将获得某种服务,该服务将向 ObservableCollection 提供新的 StockQuotes。
我的问题是:在这种情况下,StockQuote 被视为模型,我们通过 ViewModel 的 ObservableCollection 将其公开给视图。这基本上意味着,我们的视图了解模型。这不违反 M-V-VM 的整个范式吗?还是我在这里遗漏了什么......?
【问题讨论】: