2011-07-09 74 views
1

實例在XAML代碼中,我得到一個錯誤說服力不能創建的 實例此AllEmployeeViewModel類文件,實際上這個類文件存在於溶液中的文件夾,當我型可控硅:在intellsene顯示我類文件不能創建XAML在Silverlight 4.0

<UserControl.Resources> 
    <scr:AllEmployeeViewModel x:Key="empName"></scr:AllEmployeeViewModel> 
</UserControl.Resources> 
<Grid x:Name="MainGrid" Background="White" Width="400" 
    Height="407" DataContext="{Binding Source={StaticResource empName}}" > 
<Grid x:Name="grdAllEmp" DataContext="{Binding Path=EmployeeClass}"> 
    <sdk:DataGrid AutoGenerateColumns="True" Height="274" 
        HorizontalAlignment="Left" Margin="8,8,0,0" 
        Name="dgEmployee" VerticalAlignment="Top" Width="385" 
        ItemsSource="{Binding}"/> 
    <Button Content="Get All Employees" Height="23" 
      HorizontalAlignment="Left" Margin="12,288,0,0" 
      Name="btnAllEmplloyees" VerticalAlignment="Top" Width="381" 
      Command="{Binding Path=DataContext.GetEmployees,ElementName=MainGrid}"/> 
</Grid> 

我試圖綁定到數據網格,如果我忽略編譯時錯誤和運行其給未發現的錯誤的關鍵。

請讓我知道你知道solutionif,在這個問題上的工作從過去的2天

任何幫助將是巨大的 感謝。

+0

解決方案:InitializeComponent(); if(!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this)) { //拋出異常的代碼 } – happysmile

+0

您確實需要在此問題和您的「修復」中發佈代碼。例如,你確切地說,你在什麼樣的代碼旁邊沒有設計模式檢查?沒有澄清你的問題和答案都沒有用。 –

回答

0

您的類AllEmployeeViewModel是否有一個零參數構造函數?無論如何,Silverlight不能創建你的類的一個實例。

+0

是的,它有一個零參數的控制器 – happysmile

2

就在MainPage.xaml.cs中頁面

InitializeComponent(); 
     if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this)) 
     { 
      //Code that throws the exception 
     } 

它工作正常加入這一行。

+0

你確實需要在你的問題和這個「修正」的例子中發佈代碼。例如,你確切地說,你在什麼樣的代碼旁邊沒有設計模式檢查?沒有澄清你的問題和答案都沒有用。 –

0

您對EmployeeClass有約束力。這必須是某種類型的集合才能工作,但名稱EmployeeClass聽起來像是單個對象而不是集合。

您確實需要發佈視圖模型代碼,因爲我們必須猜測這一點。

我把一個簡單的例子,如果視圖模型包含:

public ObservableCollection<EmployeeClass> Employees { get; set; } 

,我填充他們用了幾樣EmployeeClass對象,

public AllEmployeeViewModel() 
{ 
    this.Employees = new ObservableCollection<EmployeeClass>(); 
    this.Employees.Add(new EmployeeClass() { Name = "One" }); 
    this.Employees.Add(new EmployeeClass() { Name = "Two" }); 

,我更改綁定到:

<Grid x:Name="grdAllEmp" DataContext="{Binding Path=Employees}"> 

看起來像這樣(沒有其他變化): enter image description here

4

我也有同樣的問題。 cannot create instance of viewmodel

只需複製該代碼,並將其放置在視圖模型

public bool IsDesignTime 
{ 
    get 
    { 
     return (Application.Current == null) || 
      (Application.Current.GetType() == typeof(Application)); 
    } 
} 




//Constructor  
public ViewModelClass() 
{ 
    if(IsDesignTime == false) 
    { 
     //Your Code 
    } 
} 
0

我得到了同樣的錯誤,我會解釋給你希望它會幫助你。 在我視圖模型的構造我正在執行一些代碼,所有的代碼是withing下面如果狀態,除非,

 
     If(!IsInDesignMode) 
     { 
      // my code 
     } 

     // Problamatic method execution point 

只是我想執行每一次的方法,但事實證明,你只有滿足上述條件才能執行代碼,否則將不會創建視圖模型實例。

因此,爲了避免這一點,你必須做的那樣:

 
     If(!IsInDesignMode) 
     { 
      // my code 
      // Problamatic method execution point 
     }  

把所有的代碼,條件內,一切都會好起來。
注:我用MVVMLight庫模型 - 視圖 - ViweModel模式一起。