2011-07-09 34 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模式一起。