Having my Viewmodel appear in namespace dropdown

2019-07-31 18:11发布

问题:

I'm trying to expose the ViewModel as a static resource on the page so that it can be easily accessible by the binding.

TestViewModel.cs

namespace Test.WPFUI.Home
{ 
    public class TestViewModel....

HelloWorldView.Xaml

xmlns:local="clr-namespace:Test.WPFUI.Home"

<UserControl.Resources>
    <local:TestViewModel x:Key="mainPageViewModel" />
</UserControl.Resources>

TestViewModel Can't be found. May I ask for some tips or suggestions Please.

Getting help from http://www.telerik.com/help/silverlight/gridview-troubleshooting-blank-cells.html

public class LoanViewModel : ScreenViewModelBase<LoanViewModel>, IRecord, INotifyPropertyChanged 
{

    public LoanViewModel(IEventAggregator events) .............

回答1:

It sounds like your initial problem was not having the full xmlns definition. You usually need both the namespace and assembly.

The easiest way to get it right, in my experience, is to let intellisense do it for you. Just start typing the namespace you want, and as long as its in a referenced project, there will be an autocomplete option.

Your second problem is due to not having a default constructor. You wrote this:

<local:TestViewModel x:Key="mainPageViewModel" />

Which will invoke the default constructor. However, you define a constructor here:

public LoanViewModel(IEventAggregator events) .............

Which removes the provided (paramaterless) default constructor. I'm going to take a wild guess and say that creating the correct IEventAggregator is not simple or desired from XAML, so I see two choices:

  1. You didn't really need that parameter in the constructor. Simply add a default constructor to your view model and you are good to go!

  2. You really need that parameter, so instantiating from XAML just isn't a good idea. Pass in your view model from somewhere else on the view's constructor.

If you feel like you can instantiate the correct object from XAML, use this post to invoke the paramaterized constructor: Calling a parameterized constructor from XAML

In my opinion, putting truly regular classes into XAML is not a good pattern to follow, so I wouldn't. By regular, I mean not related at all to the view.



标签: c# wpf mvvm