2012-02-28 42 views
0

我們正在使用Model-View-Presenter被動視圖策略構建我們的軟件。在我們的軟件上,我們有一個報告和不同類型的圖表。因此,我們必須對圖表的抽象類的功能,所有的圖表將實施:如何在MVP中爲抽象模型創建視圖和演示者

abstract class AbstractChart 
{ 
    ... 
} 

然後我們有具體類(模型),可以說,條形圖和餅圖:

class BarChart: AbstractChart 
{ 
    ... 
} 
class PieChart: AbstractChart 
{ 
    ... 
} 

報表可以包含不同圖表的種類。

class Report 
{ 
    public List<AbstractChart> Charts {get; set; } 
    ... 
} 

所以,我們必須在報表上繪製不同的圖表的一個問題:

class ReportPresenter 
{ 
    Report _report; 
    ReportView _view; 
    ... 
    FillReportView(Report report) 
    { 
     foreach(AbstractChart chart in _report.Charts) 
     { 
      // Here is the problem: How do we create correct 
      // view and presenter for abstract chart? We need to 
      // create them, so we can add chart view to _view. 
     } 
    } 
} 
+2

有沒有原因,你不使用MVVM與WPF? – 2012-02-28 14:00:02

+0

我們嘗試過MVVM,但雖然它看起來非常好,但它證明了我們的需求太複雜。 – teemu 2012-02-29 06:51:31

+1

我的經驗是MVVM *正確使用*極大地降低了**複雜性。 – 2012-02-29 10:56:00

回答

0

由於缺乏更好的想法,我通過創建一個Factory類來解決這個問題,該類爲模型創建適當的演示者。現在,我已經在他們的演示者中創建了視圖,但使用Unity之類的IoC容器會更好。

0

我只想用WPF DataTemplates告訴WPF如何繪製每個圖表類型,當它遇到的一個對象在Visual樹

<Application.Resources> 

    <DataTemplate DataType="{x:Type local:BarChart}"> 
     <local:BarChartUserControl /> 
    </DataTemplate> 

    <DataTemplate DataType="{x:Type local:PieChart}"> 
     <local:PieChartUserControl /> 
    </DataTemplate> 

</Application.Resources> 

的用戶控件背後的DataContext類型仍然是你的對象,這樣你就可以建立與期望的用戶控件是在DataContext將是BarChart型或PieChart

。例如,一個ItemsControl會提醒你使用每種類型正確的模板,沒有額外的編碼圖表的列表:

<ItemsControl ItemsSource="{Binding Charts}" /> 

或者您也可以手動添加圖表使用像一個ContentControl

<ContentControl Content="{Binding SomeChartProperty}" /> 

作爲一個側面說明對象的可視化樹,我會強烈建議切換到使用,而不是MVP MVVM。它非常適合WPF,並且是使用WPF或Silverlight時使用的標準設計模式。

+0

這將解決爲模型創建視圖對象的問題,但是誰應該創建相應的演示者? – teemu 2012-02-29 07:03:51

+0

@teemu在使用WPF時,我沒有使用過MVP,但是它聽起來像是和應用程序代碼相關,而不是UI代碼,所以我認爲它會由ViewModels創建。如果你使用WPF,我強烈推薦切換到MVVM。如果您有興趣,可以在我的博客上找到[簡單MVVM示例](http://rachel53461.wordpress.com/2011/05/08/simplemvvmexample/)。 – Rachel 2012-02-29 13:04:40

相關問題