WPF: viewmodel类型不包含任何可访问的构造函数



我在我的MainViewModel实例化我的存储库,并通过这个实例在我的孩子ViewModel(即CategoryViewModel)中使用。我得到一个

严重性代码描述项目文件行类型"CategoryViewModel"不包含任何可访问的构造函数。

错误来自我的主窗口,我已经声明了类别用户控件并将DataContext设置为CategoryViewModel:

<view:CategoryView Grid.Row="2" Grid.Column="0" Margin="5">
    <view:CategoryView.DataContext>
        <viewModel:CategoryViewModel />
    </view:CategoryView.DataContext>
</view:CategoryView>

当我在CategoryViewModel构造函数中没有任何参数时,我没有得到这个错误,所以我知道它与此有关,但不完全确定是什么导致了这个问题。我会很感激任何建议。下面是我的MainViewModelCategoryViewModel

public class MainViewModel : BindableBase
{
    private readonly IRepository _repo = new Repository();
    private CategoryViewModel _categoryViewModel;
    public MainViewModel()
    {
        _categoryViewModel = new CategoryViewModel(_repo);
    }
}
public class CategoryViewModel : BindableBase
{       
    private IRepository _repo;
    public List<Category> CategoryCollection { get; set; }
    public CategoryViewModel(IRepository repo)
    {
        _repo = repo;            
       CategoryCollection = LoadCategory();
    }
    private List<Category> LoadCategory()
    {
        return _repo.GetAllCategories();
    }
}

如果你想要一个带参数的构造函数,你有两个选择:在后面的代码中实例化你的视图模型,或者使用ObjectDataProvider类

我的做法如下:在控制。Xaml,我把它放在顶层标签(不确定如何将其转换为完整的xml表示法)

  d:DataContext="{d:DesignInstance Type=visuals:ControlPanelRadPaneVM, IsDesignTimeCreatable=True}"

control . xml .cs中,我添加了一个接受上下文的构造函数,将其标记为注入构造函数并分配了dataContext:

public partial class Shell : Window
{
    [InjectionConstructor]
    public Shell(ShellViewModel context)
    {
        DataContext = context;
        InitializeComponent();
    }
}

就是这样。现在,每当我执行container。resolve()时,我都会同时得到它们。我还没看到任何问题。但显然这是可以做到的。

相关内容

最新更新