2014-09-03 118 views
1

如果設置爲數據上下文的視圖模型在靜態類中註冊自己,則XAML設計器會使Visual Studio 2010崩潰。XAML設計器崩潰,自注冊ViewModel

查看

<Window x:Class="CTL.Editor.View.EditorWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:editor="clr-namespace:CTL.Editor.ViewModel.Editor" 
     Height="300" Width="300"> 
    <Window.DataContext> 
     <editor:EditorWindowViewModel /> 
    </Window.DataContext> 
    <Grid> 

    </Grid> 
</Window> 

視圖模型:

public EditorWindowViewModel() 
{ 
    ApplicationViewModel.EditorWindows.Add(this); 
} 

~EditorWindowViewModel() 
{ 
    ApplicationViewModel.EditorWindows.Remove(this); 
} 

有沒有解決這個辦法嗎?也許是#指令?

回答

1

對於那些尋求比Postlagerkarte的回答更詳細一點:

使用IsInDesignMode的方式,是MVVM友好如下所示。

if (DesignerProperties.GetIsInDesignMode(new DependencyObject())) 
{ 
    .... 
} 

我的問題是由事實ApplicationViewModel的構造是什麼加載配置文件,顯然Visual Studio中並沒有這樣,沒有找到文件或在正確的地方沒有搜索文件引起當它運行我的代碼。

我最終什麼事做的是:

public static bool DesignMode 
{ 
    get { return DesignerProperties.GetIsInDesignMode(new DependencyObject()); } 
} 

static ApplicationViewModel() 
{ 
    if (!DesignMode) 
    { 
     Configuration = Configuration.LoadConfigurationDocument(); 
    } 
} 

注:有上ApplicationViewModel一個配置靜態成員和加載配置一個配置類。

2

您可以使用DesignerProperties.IsInDesignMode在設計模式下禁止執行。只需在if語句中包裝代碼:if(!DesignerProperties.IsInDesignTool)

但是,通過調試設計器異常找到問題的根本原因通常是一個好主意。 Here是一本很好的文章,應該讓你開始。

+0

謝謝,這正是我正在尋找的。我計劃在訴諸代碼之前再調查一下代碼,但至少有一些選擇。 – 2014-09-03 12:45:45

+0

該問題似乎是由靜態類中的列表中的.Add()調用引起的(列表正在初始化)。 – 2014-09-04 22:52:06